在R中移动字符串
我的数据表如下:在R中移动字符串,r,R,我的数据表如下: x y z 1 head car toe 2 hand nose mouse 3 key house ball 现在,我想将head、hand和ball移至新列,并删除现有列中的单词: x y z new 1 car toe head 2 nose mouse hand 3 key house ball 你能帮帮我吗?多谢各位 Reproducible Dat
x y z
1 head car toe
2 hand nose mouse
3 key house ball
现在,我想将head、hand和ball移至新列,并删除现有列中的单词:
x y z new
1 car toe head
2 nose mouse hand
3 key house ball
你能帮帮我吗?多谢各位
Reproducible Data:
df <- data.frame(
V1 = 1:3,
x = c("head", "car", "toe"),
y = c("hand", "nose", "mouse"),
z = c("key", "house", "ball")
)
将dplyr用于类似这样的情况:让X成为用于重命名或重新排序/选择列的数据帧
library(dplyr)
X %>% rename(new=head)
或创建新的顺序或列的选择
X %>% select(x,y,z,`1`,car,toe)
数据
密码
后果
警告:这种方法将x方向的手或头优先于z方向的球。将示例数据粘贴为文本,而不是图像。更好的是,使其可复制:仅供参考:R中的数据框在概念上不是一个电子表格,您可以在其中自由地将值从一个单元格移动到另一个单元格,而是一组在许多方面长度相等的独立向量变量。
library (dplyr)
df <- data.frame(
x = c("head", "hand", "key"),
y = c("car", "nose", "house"),
z = c("toe", "mouse", "ball"),
stringsAsFactors = FALSE
)
# Add new column.
df_result <- df %>%
mutate(
new = case_when(
x %in% c("head", "hand") ~ x,
z == "ball" ~ z,
TRUE ~ NA_character_
)
)
# Remove old values.
df_result$x[df_result$x %in% c("head", "hand")] <- NA_character_
df_result$z[df_result$z == "ball"] <- NA_character_
> df_result
x y z new
1 <NA> car toe head
2 <NA> nose mouse hand
3 key house <NA> ball