根据R中匹配的列选择值

时间:2017-05-24 13:21:18

标签: r

我是R的新手(大约1周)并且有一个我无法找到答案的问题。我有一个大约100列的数据框,采用以下形式:

x_1 x_2 x_3 ... x_50 y_1 y_2 y_3 ... y_50。

我需要检查每个x列的值(例如,“01”),如果它存在于一行中,则从相应的y列中提取值。我可以轻松地使用以下代码执行此操作:

data want;
     set have;

     array x[50] x_1 - x_50;
     array y[50] y_1 - y_50;
     do i = 1 to 50;
         if x[i] = "01" then value = y[i];
         output;
     end;
run;

有什么建议吗?

3 个答案:

答案 0 :(得分:0)

未经测试

当你有一个数据集y和x时,你可以这样:(它们当然需要具有相同的尺寸)

text

答案 1 :(得分:0)

使用data.table,此解决方案将起作用:

library(data.table); library(rebus);

#generate your table
data <- data.table(a = 1:50, rowid = rep(1:50, each=50), x =round(runif(500)), y =round(runif(500)))
data
data <- dcast(data, rowid~a, value.var = c("x", "y"))

### solution

# meltdata
meltdata <- melt(data, id.vars="rowid")
# extract column names
meltdata$part <- str_match(meltdata$variable, pattern = capture(ANY_CHAR) %R% "_" %R% capture(one_or_more(DGT)))[, 2]
meltdata$number <- str_match(meltdata$variable, pattern = capture(ANY_CHAR) %R% "_" %R% capture(one_or_more(DGT)))[, 3]
# seperate x and y tables
xvalue <- meltdata[part == "x", .(rowid, number, xvalue = value)]
yvalue <- meltdata[part == "y", .(rowid, number, yvalue = value)]
#merge x and y tables
mergeddata <- merge(xvalue, yvalue, by=c("rowid", "number"))

由于您没有分享您的数据,还有额外的工作,但我认为它运作良好。

答案 2 :(得分:0)

可能不是最有效的方法,但假设您需要像SAS示例那样处理循环,这可能会产生您正在寻找的结果。

for(i in 1:length(colnames(df))){
  col <- colnames(df)[i]
  if(startsWith(col,"x")){
    for(r in 1:nrow(df))
    {
      if(df[r,col] == 1)
      {
        ycol <- sub("x","y",col)
        yval <- df[r,ycol]
        print(paste(col,"=",df[r,col],":",ycol,"=",yval))
      }
    }
  }
}