r - 根据另一列 R 中的字符创建一列
问题描述
我希望根据另一列中的标签创建一个新列。举个简单的例子,假设我有以下数据框
> df <- data.frame(label = c("AF1", "AF2", "AO1", "AO1"), somevalue = c(1, 2, 3, 4))
> df
label somevalue
1 AF1 1
2 AF2 2
3 AO1 3
4 AO1 4
我需要做的是根据“标签”中的中间字符创建一个新列。我已经设法用下面的代码做到了这一点,但我觉得必须有一种更优雅的方式来做到这一点,这是目前我所无法做到的。
> df <- df %>% mutate(newCol = NA)
> df$newCol[str_detect(df$label, "F")] <- "fairies"
> df$newCol[str_detect(df$label, "O")] <- "ogres"
> df
label somevalue newCol
1 AF1 1 fairies
2 AF2 2 fairies
3 AO1 3 ogres
4 AO1 4 ogres
提前致谢。
解决方案
这是使用基本 R 代码的简单解决方案:
df[substr(df$label,2,2)=="F","newCol"]<-"fairies"
df[substr(df$label,2,2)=="O","newCol"]<-"ogres"
df
label somevalue newCol
1 AF1 1 fairies
2 AF2 2 fairies
3 AO1 3 ogres
4 AO1 4 ogres
推荐阅读
- excel - 用变量替换用户表单名称
- ionic-framework - 与输入结合时,按钮在 ion-item 中不可见
- r - 如何在 R 中取这些平均值?
- android - Android NDK 构建
- firebase - 相当于 MySQL 事务的 firebase 数据库
- sql-server - 在 SQL 中映射列名
- c++ - 函数重载和double和long之间的混淆
- c++ - C ++ 11模板函数“隐式”转换位集
到“无符号长” - javascript - ReactJS - 如何在 URL 中获取当前页面?
- omnet++ - [osgEarth]* [Horizon] 回调中没有安装地平线信息