[英]R: Error: unexpected '=' in
I have a data frame (df), a vector of column names (foo), and a function (spaces) that calculates a value for all rows in a specified column of a df. 我有一个数据框(df),一个列名向量(foo)和一个函数(空格),该函数计算df指定列中所有行的值。 I am trying to accomplish the following:
我正在尝试完成以下任务:
I keep receiving Error: 我不断收到错误消息:
> Error: unexpected '=' in:
>" new[i] <- paste0(foo[i],".count") # New variable name
> data <- transform(data, new[i] ="
> }
> Error: unexpected '}' in " }"
Below is my code. 下面是我的代码。 Note: spaces does what I want when provided an input of a single variable of the form df$x but using transform() should allow me to forego including the prefix df$ for each variable.
注意:当提供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
}
transform(df, new[i] = spaces(foo[i]))
is not valid syntax. transform(df, new[i] = spaces(foo[i]))
是无效的语法。 You cannot call argument names by an index. 您不能通过索引调用参数名称。 Create a temporary character string and use that.
创建一个临时字符串并使用它。
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.