简体   繁体   中英

create another column based on the values on a column in R

I have a data frame called p, it content is as below:

structure(list(AGENT = c(45693, 45693, 45693, 45693, 45693, 45693, 
45693, 45693, 42627, 42627, 42627, 42627, 42627, 42627)), .Names = "AGENT", row.names = c(NA, 
-14L), class = "data.frame")

I would like to add two more columns to this data frame called p. For example, if the p$AGENT==45693, I like to set the Location to dallas, and the provider to ATT.

I haved tried something like this:

library(data.table)
p<-p[,LOCATION:=if(AGENT==45693, c("Dallas"))]

I get this error:

Error: unexpected ',' in "p<-p[,LOCATION:=if(AGENT==45693,"

is data.table the best method to accomplish this? Any ideas?

you have to make pa data.table before you can use data.table syntax on it.

p<-data.table(p)
#create(update) column called LOCATION and set it to Dallas if AGENT==45693
p[AGENT==45693,LOCATION:="Dallas"]

the first argument in the brackets is the filter and the second is called the J where you can either select columns or in this case assign a column.

The anser of @Dean is very good. Mine just to mention the fact that you can also use := assignment operator to create a vector of names. Here 2 versions:

library(data.table)
p <- data.table(dat)
p[AGENT==45693,c('LOCATION','Provider') := list("Dallas",'ATT')]

DT <- data.table(dat)
DT[AGENT==45693, `:=`(LOCATION ="Dallas", Provider = "ATT")]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM