在其他dataframe列之间添加新列
我想在我的数据框中添加一个带有“NA”的新列:在其他dataframe列之间添加新列,r,dataframe,R,Dataframe,我想在我的数据框中添加一个带有“NA”的新列: A B 1 14379 32094 2 151884 174367 3 438422 449382 但我需要它位于A列和B列之间,就像这样: A C B 1 14379 NA 32094 2 151884 NA 174367 3 438422 NA 449382 我知道如何在B列之后加C列,但这对我没有帮助。。。有人知道怎么做吗
A B
1 14379 32094
2 151884 174367
3 438422 449382
但我需要它位于A列和B列之间,就像这样:
A C B
1 14379 NA 32094
2 151884 NA 174367
3 438422 NA 449382
我知道如何在B列之后加C列,但这对我没有帮助。。。有人知道怎么做吗 通过两个步骤,您可以对列重新排序:
dat$C <- NA
dat <- dat[, c("A", "C", "B")]
A C B
1 0.596068 NA -0.7783724
2 -1.464656 NA -0.8425972
如果使用
data.table
,则可以使用函数setcolorder
。请注意,NA
存储为逻辑变量,如果要将列初始化为整数、双精度或字符列,可以使用NA_integer
、NA_real
或NA_character
乙二醇
我编写了一个函数将列附加到data.frame中。它还允许您命名列,并进行一些检查
append_col <- function(x, cols, after=length(x)) {
x <- as.data.frame(x)
if (is.character(after)) {
ind <- which(colnames(x) == after)
if (any(is.null(ind))) stop(after, "not found in colnames(x)\n")
} else if (is.numeric(after)) {
ind <- after
}
stopifnot(all(ind <= ncol(x)))
cbind(x, cols)[, append(1:ncol(x), ncol(x) + 1:length(cols), after=ind)]
}
append_col您还可以使用包tibble,它有一个非常有趣的函数(除其他函数外):add_column()
库(TIBLE)
df
library(data.table)
DT <- data.table(DF)
# add column `C` = NA
DT[, C := NA]
setcolorder(DT, c('A','C','B'))
DT
## A C B
## 1: 14379 NA 32094
## 2: 151884 NA 174367
## 3: 438422 NA 449382
setcolorder(DT[, C: = NA], c('A','B','C'))
append_col <- function(x, cols, after=length(x)) {
x <- as.data.frame(x)
if (is.character(after)) {
ind <- which(colnames(x) == after)
if (any(is.null(ind))) stop(after, "not found in colnames(x)\n")
} else if (is.numeric(after)) {
ind <- after
}
stopifnot(all(ind <= ncol(x)))
cbind(x, cols)[, append(1:ncol(x), ncol(x) + 1:length(cols), after=ind)]
}
# create data
df <- data.frame("a"=1:5, "b"=6:10)
# append column
append_col(df, list(c=1:5))
# append after an column index
append_col(df, list(c=1:5), after=1)
# or after a named column
append_col(df, list(c=1:5), after="a")
# multiple columns / single values work as expected
append_col(df, list(c=NA, d=4:8), after=1)
library(tibble)
df <- data.frame("a" = 1:5, "b" = 6:10)
add_column(df, c = rep(NA, nrow(df)), .after = 1)