Reputation: 191
I am kind of new to R and I want to apply the gsub
function in columns 6 to 12 in my data frame called x
. However, I am kind of stuck. I started using:
gsub("\\.", "",x[,c(6:12)])
But then it returned only a few rows. Then, I tried to use this:
x1<-apply(x,c(6:12),function(x) gsub("\\.", "",x))
But I got the following error:
Error in if (d2 == 0L) { : missing value where TRUE/FALSE needed
Also tried this:
for (i in x[,c(6:12)])
{a<-data.frame(gsub("\\.", "",i))}
Does anybody have a tip or a solution?
It would also be great if someone showed me how to use an apply
function and for
.
Upvotes: 4
Views: 6076
Reputation: 16856
Adding the solution using apply
from the comments, as this one really helped me:
x1 <- apply(x[,6:12], 2, function(x) gsub("\\.", "",x))
Upvotes: 0
Reputation: 422
Here is a solution in a data.table way. It worth considering when a table is big and time is a critical factor.
library(data.table) # load library
x = as.data.table(x) # convert data.frame into data.table
cols = names(x)[6:12] # define which columns to work with
x[ , (cols) := lapply(.SD, function(x) {gsub("\\.", "", x)}), .SDcols = cols] # replace
x # enjoy results
Upvotes: 4
Reputation: 18487
Here is another solution. It returns all the columns of the original dataframe
library(dplyr)
mutate_at(x, 6:12, gsub("\\.", "", .))
Upvotes: 3