[英]use sapply on a column of a data frame? - R
I have the this data frame:我有这个数据框:
df=data.frame("fg"=c("bv65","bv89"),"gh"=c(87,21))
and I need to delete the substring "bv" in the column "fg".我需要删除“fg”列中的 substring“bv”。 I did it this way:
我是这样做的:
sapply(df$fg,FUN=gsub(pattern="bv",replacement = "",x=df$fg))
but I get this error:但我收到此错误:
Error in match.fun(FUN): 'gsub(pattern = "bv", replacement = "", x = df$fg)' is not a function, character or symbol match.fun(FUN) 中的错误:'gsub(pattern = "bv", replacement = "", x = df$fg)' is not a function, character or symbol
Why?为什么?
sub
/ gsub
are vectorized. sub
/ gsub
是矢量化的。 You can use them for all the values in the column.您可以将它们用于列中的所有值。 Perhaps, you might also want to convert the values to numeric.
也许,您可能还想将值转换为数字。
df$fg <- as.numeric(sub('bv', '', df$fg))
df
# fg gh
#1 65 87
#2 89 21
Ronak's solution is the way to go since gsub()
/ sub()
can deal with vectors. Ronak 的解决方案是 go 的方式,因为
gsub()
/ sub()
可以处理向量。 But in case you wanted to know what was missing from your current approach:但是,如果您想知道当前方法中缺少什么:
sapply(df$fg, FUN = function(x) sub(pattern="bv", replacement="", x))
# Or simply
sapply(df$fg, sub, pattern="bv", replacement="")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.