Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gsub apply combination in R

Tags:

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?

like image 367
user124123 Avatar asked Mar 19 '15 16:03

user124123


Video Answer


1 Answers

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)))
like image 69
Matt Bannert Avatar answered Sep 19 '22 12:09

Matt Bannert