Pretty simple question, and I have had a quick search in google and stackoverflow. I found this in another post: In aggregate: sum not meaningful for factors.
df[] <- lapply(df, function(x) type.convert(as.character(x))) how does df[] work?
2 Answers
To add to what Roland wrote,{edit} aaagh he ninja'd me w/ his comment the point is that using DF[] retains the existing object DF with its attributes, in this case the fact that it's got two dimensions and the names a and b .
Rgames> foo<- matrix(1:6,2,3) Rgames> foo[]<-7:12 Rgames> foo [,1] [,2] [,3] [1,] 7 9 11 [2,] 8 10 12 Rgames> foo<-7:12 Rgames> foo [1] 7 8 9 10 11 12 1It invokes [<-.data.frame (i.e., the data.frame method for [<-). That way you assign a list to a data.frame. You could also do
df <- as.data.frame(lapply(df, function(x) type.convert(as.character(x)))) Example:
DF <- data.frame(a=1:2, b=3:4) DF[] <- list(c=10:11, d=12:13) # a b # 1 10 12 # 2 11 13 But compare with this:
DF <- `[<-.data.frame`(DF, , , list(c=c("a", "b"), d=c("d", "e"))) # c d # 1 a d # 2 b e VS. this:
DF <- `[<-.data.frame`(DF, 1:2, 1:2, list(c=c("a", "b"), d=c("d", "e"))) # a b #1 a d #2 b e There is also this:
DF <- as.data.frame(list(c=10:11, d=12:13)) # c d # 1 10 12 # 2 11 13 2