我有一个数据帧( df )、一个列名向量(foo)和一个函数(空格),它计算df指定列中所有行的值。我正在努力做到以下几点:
我一直收到错误:
> Error: unexpected '=' in:
>" new[i] <- paste0(foo[i],".count") # New variable name
> data <- transform(data, new[i] ="
> }
> Error: unexpected '}' in " }"
下面是我的密码。注意:空格在提供表单df$x的单个变量的输入时会做我想做的事情,但是使用transform()应该允许我放弃,包括每个变量的前缀df$。
# Create data for example
a <- c <- seq(1:5)
b <- c("1","1 2", "1 2 3","1 2 3 4","1 2 3 4 5")
d <- 10
df <- data.frame(a,b,c,d) # data fram df
foo <- c("a","b") # these are the names of the columns I want to provide to spaces
# Define function: spaces
spaces <- function(s) { sapply(gregexpr(" ", s), function(p) { sum(p>=0) } ) }
# Initialize vector with new variable names
new <- vector(length = length(foo))
# Create loop with following steps:
# (1) New variable name
# (2) Each element (e.g. "x") of foo is fed to spaces
# a new variable (e.g. "x.count") is created in df,
# this new df overwrites the old df
for (i in 1:length(foo)) {
new[i] <- paste0(foo[i],".count") # New variable name
df <- transform(df, new[i] = spaces(foo[i])) # Function and new df
}
发布于 2016-04-08 15:52:39
transform(df, new[i] = spaces(foo[i]))
不是有效的语法。不能通过索引调用参数名。创建一个临时字符串并使用该字符串。
for (i in 1:length(foo)) {
new[i] <- paste0(foo[i],".count") # New variable name
tmp <- paste0(new[i], ".counts")
df <- transform(df, tmp = spaces(foo[i])) # Function and new df
}
https://stackoverflow.com/questions/36503978
复制相似问题