[英]Need to add a column to a data frame. The data is in another vector and is only a subset of one original DF column for reference
我是R的新手,请教您。
我有一个像这样的数据框DF:
user age email address ...
user1 20 u1@domain address1 ...
user2 19 u2@domain address2 ...
user3 30 u3@domain address3 ...
...
userm 32 um@domain addressm ...
...
usern xx un@domain address4 ...
我有一个向量如下:
user1
user3
...
userm
我需要具备以下条件:
user age email address newcol ...
user1 20 u1@domain address1 yes ...
user2 19 u2@domain address2 no ...
user3 30 u3@domain address3 yes ...
...
userm 32 um@domain addressm yes ...
...
usern xx un@domain address4 no ...
简而言之,在DF中添加一个新列,其中不包含(默认情况下),如果对应用户在矢量中,则包含yes。
任何建议表示赞赏,谢谢您的时间。
为了扩展乔兰的答案:
假设您的data.frame
名为df。 在data.frame
名为newcol的列:
df$newcol <- 'no'
如果它们是您向量的%in%
,则将newcol中的值更改为“ yes”(我假设其名为vec)。
df$newcol[df$user %in% vec] <- 'yes'
您也可以使用ifelse
一步完成此ifelse
:
df$newcol <- ifelse(df$user %in% vec, 'yes', 'no')
或者,如果您想变得棘手,可以使用merge(..., all=TRUE)
...
这可能不是最有效的示例,但它似乎有效:
data<-data.frame(c(1,2,3,4,5),c("a","b","c","d","e"));
colnames(data)<-c("numbers","names");
lookup<-c("a","d","e")
data$newcol<-rep("no",dim(data)[1])
for(i in 1:length(lookup)){
store<-which(data$names==lookup[i])
data$newcol[store]<-"yes";
}
你可以这样
DF$newcol <- 'no'
DF$newcol[DF$user %in% newVector] <- 'yes'
或者这样
DF$newcol <- ifelse(DF$user %in% newVector, 'yes', no)
前者效率更高
您可以简单地使用%in%函数
df$newcol <- ifelse(df$user %in% vec, 'yes', 'no')
要检测向量中是否存在您的值,可以直接合并2个数据帧。 这对于大型数据集尤其有用,因为由于多对多匹配,IFelse语句或%in%语句可能会花费更多时间。
例如。
vec=data.frame(user=vec) #converting vector to dataframe
DF <-merge(DF,unique(vec),by="user",all.x=T) #similar to left join in sql
DF$newcol<- "yes" #creating a new column having all values as yes
DF$newcol[is.na(DF$user2)]<- "no" #all the rows which were not present in the vector will be NAs in the newly joined column hence substituting these values as "no"
vNoYes <- c("No","Yes")# vector with new codes
idx <- (df$user %in% v)+1L# position of codes in data frame
df$newcol <- vNoYes[idx]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.