my question is an extension to the previously answered one here:
Add multiple columns to R data.table in one function call?
I'm having problems assigning multiple new columns if the data.table has a key according to which I subset. Example:
library(data.table)
example(data.table)
DT[J("a")]
x y v m
1: a 1 42 42
2: a 3 42 42
3: a 6 42 42
i.e. DT has a key(DT) = c("x", "y")
, and I want to assign 2 new columns new1
and new2
in one call, similar to the above solution. I do this:
DT[J("a"),c("new1","new2") := list(c(1,2,3),c(3,2,1)),with=FALSE]
but I get that
x y v m new1
1: a 1 42 42 1
2: a 3 42 42 2
3: a 6 42 42 3
4: b 1 4 5 NA
5: b 3 5 5 NA
6: b 6 6 5 NA
7: c 1 7 8 NA
8: c 3 8 8 NA
9: c 6 9 8 NA
i.e. behaviour as expected (assign values to where x==a, NA else), but only for the first column. Is that my mistake or is it a bug?
Notice that without subsetting DT, this works perfectly:
DT[,c("new1","new2") := list(c(1,2,3),c(3,2,1)),with=FALSE]
x y v m new1 new2
1: a 1 42 42 1 3
2: a 3 42 42 2 2
3: a 6 42 42 3 1
4: b 1 4 5 1 3
5: b 3 5 5 2 2
6: b 6 6 5 3 1
7: c 1 7 8 1 3
8: c 3 8 8 2 2
9: c 6 9 8 3 1
How do I concatenate two columns in R? To concatenate two columns you can use the <code>paste()</code> function. For example, if you want to combine the two columns A and B in the dataframe df you can use the following code: <code>df['AB'] <- paste(df$A, df$B)</code>.
You create DataColumn objects within a table by using the DataColumn constructor, or by calling the Add method of the Columns property of the table, which is a DataColumnCollection. The Add method accepts optional ColumnName, DataType, and Expression arguments and creates a new DataColumn as a member of the collection.
For adding a column to a Matrix in we use cbind() function. To know more about cbind() function simply type ? cbind() or help(cbind) in R.
Well spotted: it's a new bug. Please file a bug.report(package="data.table")
.
Thanks.
===
Now fixed in v1.8.3. Bug#2215 and latest NEWS.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With