[R] R column assignment fails for lists

David Winsemius dwinsemius at comcast.net
Wed May 4 08:18:51 CEST 2016


> On May 3, 2016, at 4:13 PM, Yasir Suhail <yasir.suhail at gmail.com> wrote:
> 
> Dear R developers and users,
> 
> Consider the object :
> 
>> a <- data.frame(a=c(1,2), b=c(2,3), c=c("a,b","c,d"), stringsAsFactors = F)
>> a$c <- strsplit(a$c, ",")
> 
> Re-assignment works fine for columns 1 and 2, but fails for column 3. If a
> is a valid object, the assignment should work.

Try working with a 3 row dataframe. Then your misconceptions about how this proposed assignment will be more prominent because the dimensions would be wrong.

Here's an alternate approach:

> a <- data.frame(a=c(1,2,3), b=c(2,3,4), c=c("a,b","c,d", "e,f"), stringsAsFactors = F)
> strsplit(a$c, ",")
[[1]]
[1] "a" "b"

[[2]]
[1] "c" "d"

[[3]]
[1] "e" "f"

> do.call(rbind, strsplit(a$c, ",") )
     [,1] [,2]
[1,] "a"  "b" 
[2,] "c"  "d" 
[3,] "e"  "f" 


> str(cbind(a[-3] , do.call(rbind, strsplit(a$c, ",") ) ,stringsAsFactors=FALSE) )
'data.frame':	3 obs. of  4 variables:
 $ a: num  1 2 3
 $ b: num  2 3 4
 $ 1: chr  "a" "c" "e"
 $ 2: chr  "b" "d" "f"

-- 
David.
> 


>> a[,1] <- a[,1]
>> a[,2] <- a[,2]
>> a[,3] <- a[,3]
> Warning message:
> In `[<-.data.frame`(`*tmp*`, , 3, value = list(c("a", "b"), c("c",  :
>  provided 2 variables to replace 1 variables
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius
Alameda, CA, USA



More information about the R-help mailing list