想象一下以下数据集(列向量):
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
Run Code Online (Sandbox Code Playgroud)
现在我想构建一个新的向量来获取值,"a"在第五个位置.所以得到的df应如下所示:
df_new
a new
1 AB3474 7
2 AB3482 8
3 AB3458 5
4 AB3487 8
5 AB3471 7
6 AB3452 5
Run Code Online (Sandbox Code Playgroud)
我对分裂的字符串(使用sapply和strsplit)进行"sapplied" ,但我想有更简单,更有希望更快的方法来解决这个问题.
有什么建议?
用这个:
df_new <- within(df, new <- substr(a, 5, 5))
Run Code Online (Sandbox Code Playgroud)
结果:
a new
1 AB3474 7
2 AB3482 8
3 AB3458 5
4 AB3487 8
5 AB3471 7
6 AB3452 5
Run Code Online (Sandbox Code Playgroud)
编辑:回答以下评论:
within(df, new <- paste0(substr(a, 5, 5), ifelse(as.numeric(substr(a, 6, 6))>5, "b", "a")))
Run Code Online (Sandbox Code Playgroud)
结果:
a new
1 AB3474 7a
2 AB3482 8a
3 AB3458 5b
4 AB3487 8b
5 AB3471 7a
6 AB3452 5a
Run Code Online (Sandbox Code Playgroud)
请注意,这as.numeric是为了避免词法比较.