[R] R column assignment fails for lists

Jim Lemon drjimlemon at gmail.com
Wed May 4 03:48:13 CEST 2016


Hi Yasil,
If you look at what happens to a[,3] after the "strsplit" it is easy:

> a[,3]
[1] "a,b" "c,d"

Here a[,3] is two strings

a$c <- strsplit(a$c, ",")
> a[,3]
[[1]]
[1] "a" "b"

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

Now a[,3] is a two element list. What R probably did was to take the
first component of a[,3] to replace the existing two values. Now if
you don't try to fool R:

> a[,3]<-list(a[,3])
> a$c
[[1]]
[1] "a" "b"

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

Jim


On Wed, May 4, 2016 at 9:13 AM, 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.
>
>> 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.



More information about the R-help mailing list