r如何让新增加的列出现在第一列 r如何调整新增加的列的位置

2023-11-19

https://www.cnblogs.com/liujiaxin2018/p/16211983.html

1、任意位置插入列

复制代码
> a <- letters[1:5]
> b <- LETTERS[1:5]
> c <- sample(1:10,5)
> d <- sample(letters[1:10],5)
> e <- data.frame(a, b, c, d)
> e                       ## 测试data.frame
  a b c d
1 a A 5 f
2 b B 6 c
3 c C 1 j
4 d D 3 d
5 e E 4 e
> xc <- 11:15
> cbind(xc, e)           ## 在第一列前插入列
  xc a b c d
1 11 a A 5 f
2 12 b B 6 c
3 13 c C 1 j
4 14 d D 3 d
5 15 e E 4 e
> cbind(e, xc)           ## 在最后一列后插入列
  a b c d xc
1 a A 5 f 11
2 b B 6 c 12
3 c C 1 j 13
4 d D 3 d 14
5 e E 4 e 15
> cbind(e[,1:2], xc, e[,3:ncol(e)])    ## 在2、3列之间插入列
  a b xc c d
1 a A 11 5 f
2 b B 12 6 c
3 c C 13 1 j
4 d D 14 3 d
5 e E 15 4 e

r如何调整新增加的列的位置

dt <- data.frame(v1=1:3,
                 v2=4:6,
                 v3=letters[1:3],
                 v4=LETTERS[1:3])
dt
dt1 <- dt[,c(1,4,3,2)] 
dt1

或者使用dplyr::select()

比如:

dat %>% select(x1, x3, x2, x4)

非常感谢您的指导,再请教一下,如果我的数据框有很多列,我只要调换其中几列,其他列要保留不动,该怎么 …
用dplyr::select()的办法就是在括号里面加个everything()

比如:

dat %>% select(x1, x3, x2, x4, everything())

https://zhuanlan.zhihu.com/p/94476408

一. 创建新列
用 dplyr 包中的 mutate() 创建或修改列:

iris %>%
  as_tibble(iris) %>%
  mutate(new_column = "recycle_me")

在这里插入图片描述
若只给新列提供长度为 1 的向量,则循环使用得到值相同的一列;正常是以长度等于行数的向量赋值:

iris %>%
  as_tibble(iris) %>%  
  mutate(new_column = rep_len(month.name, length.out=n()))

在这里插入图片描述
注: n() 返回group size, 未分组则为总行数。

二. 计算新列
用数据框的列计算新列,若修改当前列,只需要赋值给原列名。

iris %>%
  as_tibble(iris) %>%
  mutate(add_all = Sepal.Length + Sepal.Width + Petal.Length + Petal.Width)

在这里插入图片描述
注意,不能用sum(), 它会将整个列的内容都加起来,类似的还有 mean().

在同一个 mutate() 中可以同时创建或计算多个列,它们是从前往后依次计算,所以可以使用前面新创建的列。例如,

计算 iris 中所有 Petal.Length 的中位数;
创建标记列,若 Petal.Length 大于中位数则为 TRUE,否则为 FALSE;
用 as.numeric() 将 TRUE/FALSE 转化为 1/0

iris %>%
  as_tibble() %>%
  mutate(median_petal_length = median(Petal.Length),
         has_long_petals = Petal.Length > median_petal_length,
         has_long_petals = as.numeric(has_long_petals)) %>%  
  select(Petal.Length, median_petal_length, has_long_petals) 

在这里插入图片描述
非常感谢您的指导,再请教一下,如果我的数据框有很多列,我只要调换其中几列,其他列要保留不动,该怎么 …
用dplyr::select()的办法就是在括号里面加个everything()

iris %>%
  as_tibble() %>%
  mutate(median_petal_length = median(Petal.Length),
         has_long_petals = Petal.Length > median_petal_length,
         has_long_petals = as.numeric(has_long_petals)) %>%  
  select(Petal.Length, median_petal_length, has_long_petals,everying()) 
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

r如何让新增加的列出现在第一列 r如何调整新增加的列的位置 的相关文章

随机推荐