删除部分字符串并在R中创建变量时遇到问题

时间:2016-08-03 12:14:37

标签: r string variables

我名字中的_mean变量很少。我想找到这些变量并从名称中删除_mean,同时为它们创建变量moment = mean。我使用下面的代码:

for (i in 1:length(files)){                                   #looping through files 
  dflist[[i]] <- read.dta13(files[i], nonint.factors = TRUE)  #reading the files into R

  if(grepl("_mean", colnames(dflist[[i]])) == TRUE){  #locating variables with _mean
    dflist[[i]]$moment <- "mean"                   #creating moment=mean variable
    str_replace(dflist[[i]], "\\_mean.*", "")}    #removing _mean from string names
}

然而,这给了我以下错误:

1: In if (grepl("_mean", colnames(dflist[[i]])) == TRUE) { :
  the condition has length > 1 and only the first element will be used

并且不对变量进行任何调整。

输出应如下所示: 前

|variable1_mean|variable2_mean|
|24            |25            |

|moment| variable1 | variable2|
|mean  |   24      |     25   |

2 个答案:

答案 0 :(得分:1)

我们可以使用sub

执行此操作
names(df1) <- sub("_.*", "", names(df1))
df1$moment <- "mean"

答案 1 :(得分:0)

我会做这样的事情:

names <- colnames(df)
for (i in 1:length(names))
{
  names[i] <- gsub("_mean", "", names[i])
}
colnames(df) <- names

您可以使用其中一个for函数

代替apply循环