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

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()) 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

生信小博士

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值