使用R中的循环在现有数据框中创建列

时间:2018-03-23 14:47:22

标签: r loops

我正在尝试基于四个变量在现有数据框架中创建四列。由于它们都使用相同的逻辑,我决定进行循环,而不是复制和粘贴代码4次。但是,我遇到了循环问题。下面是我为循环编写的代码。

names<-c("a 1", "b 1", "c 1", "d 1")

for (k in names){ 

Large_Data$column_k <- ifelse(Large_Data$`k`== "I-2", 2,
                                +    ifelse(Large_Data$`k`== "I-3", 3,
                                +    ifelse(Large_Data$`k`== "I-4", 4,
                                +    ifelse(Large_Data$`k`== "I-5", 5,
                                +    ifelse(Large_Data$`k`== "I-6", 6,
                                +    ifelse(Large_Data$`k`== "I-7", 7,
                                +    ifelse(Large_Data$`k`== "S-1", 8,
                                +    ifelse(Large_Data$`k`== "S-2", 9,
                                +    ifelse(Large_Data$`k`== "S-3", 10,
                                +    ifelse(Large_Data$`k`== "S-4", 11,
                                +    ifelse(Large_Data$`k`== "P-1", 12,
                                +    ifelse(Large_Data$`k`== "P-2", 13,
                                +    ifelse(Large_Data$`k`== "P-3", 14,
                                +    ifelse(Large_Data$`k`== "D-1", 15,
                                +    ifelse(Large_Data$`k`== "D-2", 16,
                                99)))))))))))))))


}

对于这个问题,我将不胜感激。谢谢。

2 个答案:

答案 0 :(得分:1)

使用某种查找表并合并两个dataframes而不是所有ifelse语句,似乎可以更轻松地解决您的问题。

示例:

lookup.table = structure(list(cyl = c(4L, 6L, 8L), new = structure(c(2L, 3L, 
1L), .Label = c("eight", "four", "six"), class = "factor")), .Names = c("cyl", 
"new"), class = "data.frame", row.names = c(NA, -3L))

merge(mtcars,lookup.table,by="cyl")

答案 1 :(得分:0)

如何构建查找表

library(data.table)
letter=c('I','S','P','D')
start=c(2,1,1,1)
end=c(7,4,3,2)
label=2:16 # correspond to the I-2, I-3,..S1,S2,... values in that order
code.table=data.table(letter,start,end)
code.vector=unlist(apply(code.table,1,function(x) paste(x[1],x[2]:x[3],sep='-')))
lookup.table=data.table(code=code.vector,label=label)

构建查找表后,您可以创建一个合并表并获取标签的函数,并将此函数应用于所有列名称

getlabel=function(x)    merge(Large_Data,lookup.table,by.x=x,by.y="code",all.x=TRUE,sort=F)$label
lapply(names,function(x) Large_Data[,paste(x,"label",sep="_"):=getlabel(x)])