Reputation: 4242
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. 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.
# 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
}
Upvotes: 0
Views: 11358
Reputation: 70633
transform(df, new[i] = spaces(foo[i]))
is not valid syntax. 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
}
Upvotes: 2