Reputation: 197
I have tried to find an answer to this but I have failed frequently. I have a dataframe with a column of strings. I want to count the number of characters in each entry of the column and replace the string column with the counts.
data[,29]=apply(data[,29],nchar())
Out[2]: Error in match.fun(FUN): argument "FUN" is missing, with no default
Error in match.fun(FUN): argument "FUN" is missing, with no default
Upvotes: 8
Views: 63773
Reputation: 89
With data.frames
you need to specify the MARGIN
parameter of apply
, which means, wether you want to apply the funcion to the columns or the rows.
# Apply to rows
apply(data[,29],1,nchar)
## apply(X=data[,29],MARGIN=1,FUN=nchar)
# Apply to columns
apply(data[,29],2,nchar)
Upvotes: 1
Reputation: 545528
There are several problems with the code.
First, apply
operators on a matrix or data.frame
. You probably meant to use sapply
instead.
Second, nchar()
calls nchar
without any argument. You want nchar
— i.e. the function name, without calling it (the calling will happen inside sapply
):
data[, 29] = sapply(data[,29], nchar)
Upvotes: 11