string - 对字符向量的 strsplit 进行 sapply 的替代方法

标签 string r split

想象以下数据集(列向量):

df <- data.frame(a=c("AB3474","AB3482","AB3458","AB3487","AB3471","AB3452"))
df
       a
1 AB3474
2 AB3482
3 AB3458
4 AB3487
5 AB3471
6 AB3452

现在我想构建一个新的向量来获取“a”在第五个位置上的值。所以生成的 df 应如下所示:

df_new
       a new
1 AB3474   7
2 AB3482   8
3 AB3458   5
4 AB3487   8
5 AB3471   7
6 AB3452   5

我“sapplied”了分割的字符串(使用sapplystrsplit),但我想有更简单且希望更快的方法来解决这个问题。

有什么建议吗?

最佳答案

使用这个:

df_new <- within(df, new <- substr(a, 5, 5))

结果:

       a new
1 AB3474   7
2 AB3482   8
3 AB3458   5
4 AB3487   8
5 AB3471   7
6 AB3452   5

编辑:回答下面的评论:

within(df, new <- paste0(substr(a, 5, 5), ifelse(as.numeric(substr(a, 6, 6))>5, "b", "a")))

结果:

       a new
1 AB3474  7a
2 AB3482  8a
3 AB3458  5b
4 AB3487  8b
5 AB3471  7a
6 AB3452  5a

请注意,首选 as.numeric 以避免词法比较。

关于string - 对字符向量的 strsplit 进行 sapply 的替代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18187408/

相关文章:

将 R 中的 NA 替换为当前的 rollapply 值

javascript - 使用未知长度字符串拆分 JavaScript 字符串,例如\n

python - 如何在python中的较大字符串之间附加较小的字符串?

r - R : no applicable method for 'st_centroid' applied to an object of class "NULL" 错误

java - 从给定字符串创建字母和数字组的简单方法

使用 data.table 包 reshape 数据

c# - 按字符拆分字符串,但跳过某些字符组合

python 查找软件唯一版本的方法

javascript - 如何使用javascript获取base64编码图像的地址

c++ - 以下声明之间有什么区别?