简体   繁体   English

R:错误:出现意外的“ =”

[英]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: 我正在尝试完成以下任务:

  1. Private foo as input to spaces 私有foo作为空格的输入
  2. Spaces operates on each element of foo matching a column name in df 空格对与df中的列名匹配的foo的每个元素进行操作
  3. For each column spaces operates on, store the output of spaces in a new column of df with a column name produced by concatenating the name of the original column and ".counts". 对于每个操作的空格,将空格的输出存储在df的新列中,该列的名称通过将原始列的名称和“ .counts”串联而产生。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM