user124123
user124123

Reputation: 1683

gsub apply combination in R

I am trying to use gsub on every column of a dataframe to remove some characters, I have tried using apply to do this without success:

data<-apply(data,2, function(x) gsub("£","",data[x]))

returns error

Error in `[.data.frame`(data, x) : undefined columns selected

I know it works if I do

for(i in 1: length(data)){data[,i]<-gsub("£","",data[,i]) }

But why doesn't the apply call work?

Upvotes: 8

Views: 12071

Answers (1)

Matt Bannert
Matt Bannert

Reputation: 28264

Here's the next best reproducible example. Though there might be a better / faster (vectorized) way if I thought a little harder. But since you asked for apply:

# just turn it to characters in order to 
# turn . to , ... was just the first dataset that came to
# but as character should not be necessary for your data
ds[] <- sapply(mtcars,function(x) gsub("\\.",",",as.character(x)))

Upvotes: 11

Related Questions