Reputation: 214
I have the following line of code which takes all string after the "_" character:
gsub(" ","",unlist(strsplit(dtt$id,"[,_]")))[2]
and it works fine.However, when I try to put it into an apply function in order to do the same to all of the id's in the dtt table, I'm getting the follwing error:
apply(dtt,1,gsub(" ","",unlist(strsplit(dtt$id,"[,_]")))[2])
Error in get(as.character(FUN), mode = "function", envir = envir)
dtt:
id grade
1_Tim 89
2_Jack 100
3_Jeff 55
Upvotes: 0
Views: 215
Reputation: 50668
Is this what you're after?
# Sample data
dtt <- read.table(text =
"id grade
1_Tim 89
2_Jack 100
3_Jeff 55", header = T)
apply(dtt, 1, function(x) gsub(" ","", unlist(strsplit(x, "[,_]")))[2])
#[1] "Tim" "Jack" "Jeff"
There is actually no need for apply
here. You can just do:
gsub("\\d+_", "", dtt$id)
#[1] "Tim" "Jack" "Jeff"
Or if you want to clean-up id
entries in your dtt
:
transform(dtt, id = gsub("\\d+_", "", id));
# id grade
#1 Tim 89
#2 Jack 100
#3 Jeff 55
Upvotes: 1