【问题标题】:Add new variable to specific position in dataframe without specifying a numbered position将新变量添加到数据框中的特定位置而不指定编号位置
【发布时间】:2019-09-20 10:24:36
【问题描述】:

在 Stata 中,我可以在另一个变量之后或之前创建一个变量。例如。 gen age=., after(sex)

我想在 R 中做同样的事情。有可能吗?

我的数据库有300个变量,所以我不想数它来发现它的编号位置,而且我可能会不时改变。

【问题讨论】:

  • 您能解释一下gen age=., after(sex) 的作用吗?
  • 它在性别列之后的列中创建具有所有缺失值的变量年龄。

标签: r variables


【解决方案1】:

你可以这样做:

library(tibble) 

data <- data.frame(a = c(1,2,3), b = c(1,2,3), c = c(1,2,3))

add_column(data, d = "", .after = "b")

# a b d c
# 1 1   1
# 2 2   2
# 3 3   3

或者另一种方式是:

data.frame(append(data, list(d = ""), after = match("b", names(data))))

【讨论】:

  • 谢谢你,马特。不幸的是,我的安全环境中没有安装“tibble”,但我会要求 IT 为我添加这个包。
  • @mariana,我回答中的第二种方式不需要tibble
  • 我已经完成了:data.frame(append(patients$birth_kg, list(patients$birth_kg =birth_gr/1000), after = match (patients$birth_gr))) 其中 patients 是我的数据集, birth_kg 我正在创建的变量和birth_gr 已经存在的变量。但是,它没有奏效。
  • 试试data.frame(append(patients, list(birth_kg = patients$birth_gr/1000), after = match ("birth_gr", names(patients))))
【解决方案2】:

首先将新列添加到数据框的末尾。然后,找到您希望新列实际出现的列的索引,并对其进行插值:

df$new_col <- ...
index <- match("col_before", names(df))
df <- df[, c(names(df)[c(1:index)], "new_col", names(df)[c((index+1):(ncol(df)-1))])]

示例:

df <- data.frame(v1=c(1:3), v2=c(4:6), v3=c(7:9))
df$new_col <- c(7,7,7)
index <- match("v2", names(df))
df <- df[, c(names(df)[c(1:index)], "new_col", names(df)[c((index+1):(ncol(df)-1))])]
df

  v1 v2 new_col v3
1  1  4       7  7
2  2  5       7  8
3  3  6       7  9

【讨论】:

  • 非常感谢,蒂姆。对于像我这样的初学者来说,代码似乎很复杂,但它确实有效。
  • 我已经做到了。但是,由于我是新成员,因此不考虑我的投票。对不起。
猜你喜欢
  • 2013-01-27
  • 1970-01-01
  • 2013-04-21
  • 1970-01-01
  • 2018-05-03
  • 2011-04-01
  • 1970-01-01
  • 2010-10-20
  • 2015-10-16
相关资源
最近更新 更多