Добавить (вставить) столбец между двумя столбцами в data.frame

У меня есть фрейм данных со столбцами a, b 9X_data.frame и c. Я хочу добавить новый столбец d между 9X_r-df b и c.

Я знаю, что могу просто добавить d 9X_r в конце, используя cbind, но как я могу вставить его 9X_pandas-df между двумя столбцами?

120
1

  • позволяет ли функция mutate ...
13
Общее количество ответов: 13

Ответ #1

Ответ на вопрос: Добавить (вставить) столбец между двумя столбцами в data.frame

Я бы посоветовал вам использовать функцию 9X_data.frame add_column() из пакета tibble.

library(tibble)
dataset <- data.frame(a = 1:5, b = 2:6, c=3:7)
add_column(dataset, d = 4:8, .after = 2)

Обратите внимание, что вы можете 9X_dataframe использовать имена столбцов вместо индекса 9X_data-frame столбца:

add_column(dataset, d = 4:8, .after = "b")

Или используйте аргумент .before вместо 9X_df .after, если это удобнее.

add_column(dataset, d = 4:8, .before = "c")

108
1

  • Я убрал именование. Кажется, это не добавляет многого, и хотя Хэдли указан как * автор * пакета, Кирилл Мюллер указан как [создатель и сопро ...

Ответ #2

Ответ на вопрос: Добавить (вставить) столбец между двумя столбцами в data.frame

Добавьте в новый столбец:

df$d <- list/data

Затем вы можете 9X_r изменить их порядок.

df <- df[, c("a", "b", "d", "c")]

54
2

  • Я должен упомянуть, что setcolorder предназначен для d ...

Ответ #3

Ответ на вопрос: Добавить (вставить) столбец между двумя столбцами в data.frame

Вы можете изменить порядок столбцов с помощью 9X_inserts [или расположить столбцы в желаемом порядке.

d <- data.frame(a=1:4, b=5:8, c=9:12)
target <- which(names(d) == 'b')[1]
cbind(d[,1:target,drop=F], data.frame(d=12:15), d[,(target+1):length(d),drop=F])

  a b  d  c
1 1 5 12  9
2 2 6 13 10
3 3 7 14 11
4 4 8 15 12

26
2

  • Это отличный ответ. Но я должен признать, что э ...

Ответ #4

Ответ на вопрос: Добавить (вставить) столбец между двумя столбцами в data.frame

Предполагая, что c всегда следует сразу за 9X_dataframes b, этот код добавит столбец после b независимо 9X_r от того, где b находится в вашем data.frame.

> test <- data.frame(a=1,b=1,c=1)
> test
  a b c
1 1 1 1

> bspot <- which(names(test)=="b")

> data.frame(test[1:bspot],d=2,test[(bspot+1):ncol(test)])
  a b d c
1 1 1 2 1

Или, возможно, более 9X_data.frame естественно:

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

18
0

Ответ #5

Ответ на вопрос: Добавить (вставить) столбец между двумя столбцами в data.frame

Создайте пример data.frame и добавьте к 9X_dataframes нему столбец.

df = data.frame(a = seq(1, 3), b = seq(4,6), c = seq(7,9))
df['d'] <- seq(10,12)
df

  a b c  d
1 1 4 7 10
2 2 5 8 11
3 3 6 9 12

Упорядочить по индексу столбца

df[, colnames(df)[c(1:2,4,3)]]

или 9X_r-df по названию столбца

df[, c('a', 'b', 'd', 'c')]

Результат

  a b  d c
1 1 4 10 7
2 2 5 11 8
3 3 6 12 9

9
0

Ответ #6

Ответ на вопрос: Добавить (вставить) столбец между двумя столбцами в data.frame

Вы хотите добавить столбец z в старый фрейм 9X_r-language данных (old.df) определяется столбцами x 9X_r-language и y.

z = rbinom(1000, 5, 0.25)
old.df <- data.frame(x = c(1:1000), y = rnorm(1:1000))
head(old.df)

Определите новый фрейм данных с именем 9X_dataframes new.df

new.df <- data.frame(x = old.df[,1], z, y = old.df[,2])
head(new.df)

4
0

Ответ #7

Ответ на вопрос: Добавить (вставить) столбец между двумя столбцами в data.frame

Вот быстрый и грязный способ вставить столбец 9X_r в определенную позицию во фрейме данных. В 9X_data.frame моем случае у меня есть 5 столбцов в исходном 9X_rstats фрейме данных: c1, c2, c3, c4, c5, и я вставлю новый столбец 9X_rstats c2b между c2 и c3.

1) Сначала создадим тестовый 9X_pandas-df фрейм данных:

> dataset <- data.frame(c1 = 1:5, c2 = 2:6, c3=3:7, c4=4:8, c5=5:9)
> dataset
  c1 c2 c3 c4 c5
1  1  2  3  4  5
2  2  3  4  5  6
3  3  4  5  6  7
4  4  5  6  7  8
5  5  6  7  8  9

2) Добавьте новый столбец c2b в 9X_dataframes конец нашего фрейма данных:

> dataset$c2b <- 10:14
> dataset
  c1 c2 c3 c4 c5 c2b
1  1  2  3  4  5  10
2  2  3  4  5  6  11
3  3  4  5  6  7  12
4  4  5  6  7  8  13
5  5  6  7  8  9  14

3) Измените порядок 9X_insert фрейма данных на основе индексов столбцов. В 9X_r-df моем случае я хочу вставить новый столбец 9X_data-frame (6) между существующими столбцами 2 и 3. Я 9X_rstats делаю это, обращаясь к столбцам в моем фрейме 9X_data-frame данных с помощью вектора c(1:2, 6, 3:5), который эквивалентен 9X_base-r c(1, 2, 6, 3, 4, 5).

> dataset <- dataset[,c(1:2, 6, 3:5)]
> dataset
  c1 c2 c2b c3 c4 c5
1  1  2  10  3  4  5
2  2  3  11  4  5  6
3  3  4  12  5  6  7
4  4  5  13  6  7  8
5  5  6  14  7  8  9

Вот!

4
0

Ответ #8

Ответ на вопрос: Добавить (вставить) столбец между двумя столбцами в data.frame

Простое решение. Во фрейме данных с 5 столбцами, если 9X_inserts вы хотите вставить еще один столбец между 9X_base-r 3 и 4 ...

tmp <- data[, 1:3]
tmp$example <- NA # or any value.
data <- cbind(tmp, data[, 4:5]

4
0

Ответ #9

Ответ на вопрос: Добавить (вставить) столбец между двумя столбцами в data.frame

Как бы то ни было, я написал функцию для 9X_base-r этого:

[удалено]


Я обновил эту функцию, добавив 9X_base-r в нее функции before и after, и по умолчанию для place установлено 9X_insert значение 1. Она также поддерживает совместимость 9X_rstats таблиц данных:

#####
# FUNCTION: InsertDFCol(colName, colData, data, place = 1, before, after)
# DESCRIPTION: Takes in a data, a vector of data, a name for that vector and a place to insert this vector into
# the data frame as a new column. If you put place = 3, the new column will be in the 3rd position and push the current
# 3rd column up one (and each subsuquent column up one). All arguments must be set. Adding a before and after
# argument that will allow the user to say where to add the new column, before or after a particular column.
# Please note that if before or after is input, it WILL override the place argument if place is given as well. Also, place
# defaults to adding the new column to the front.
#####

InsertDFCol <- function(colName, colData, data, place = 1, before, after) {

  # A check on the place argument.
  if (length(names(data)) < place) stop("The place argument exceeds the number of columns in the data for the InsertDFCol function. Please check your place number")
  if (place <= 0 & (!missing(before) | !(missing(after)))) stop("You cannot put a column into the 0th or less than 0th position. Check your place argument.")
  if (place %% 1 != 0 & (!missing(before) | !(missing(after)))) stop("Your place value was not an integer.")
  if (!(missing(before)) & !missing(after)) stop("You cannot designate a before AND an after argument in the same function call. Please use only one or the other.")

  # Data Table compatability.
  dClass <- class(data)
  data <- as.data.frame(data)

  # Creating booleans to define whether before or after is given.
  useBefore <- !missing(before)
  useAfter <- !missing(after)

  # If either of these are true, then we are using the before or after argument, run the following code.
  if (useBefore | useAfter) {

    # Checking the before/after argument if given. Also adding regular expressions.
    if (useBefore) { CheckChoice(before, names(data)) ; before <- paste0("^", before, "$") }
    if (useAfter) { CheckChoice(after, names(data)) ; after <- paste0("^", after, "$") }

    # If before or after is given, replace "place" with the appropriate number.
    if (useBefore) { newPlace <- grep(before, names(data)) ; if (length(newPlace) > 1) { stop("Your before argument matched with more than one column name. Do you have duplicate column names?!") }}
    if (useAfter) { newPlace <- grep(after, names(data)) ; if (length(newPlace) > 1) { stop("Your after argument matched with more than one column name. Do you have duplicate column names?!") }}
    if (useBefore) place <- newPlace # Overriding place.
    if (useAfter) place <- newPlace + 1 # Overriding place.

  }

  # Making the new column.
  data[, colName] <- colData

  # Finding out how to reorder this.
  # The if statement handles the case where place = 1.
  currentPlace <- length(names(data)) # Getting the place of our data (which should have been just added at the end).
  if (place == 1) {

    colOrder <- c(currentPlace, 1:(currentPlace - 1))

  } else if (place == currentPlace) { # If the place to add the new data was just at the end of the data. Which is stupid...but we'll add support anyway.

    colOrder <- 1:currentPlace

  } else { # Every other case.

    firstHalf <- 1:(place - 1) # Finding the first half on columns that come before the insertion.
    secondHalf <- place:(currentPlace - 1) # Getting the second half, which comes after the insertion.
    colOrder <- c(firstHalf, currentPlace, secondHalf) # Putting that order together.

  }

  # Reordering the data.
  data <- subset(data, select = colOrder)

  # Data Table compatability.
  if (dClass[1] == "data.table") data <- as.data.table(data)

  # Returning.
  return(data)

}

Я понял, что также не включил 9X_pandas-df CheckChoice:

#####
# FUNCTION: CheckChoice(names, dataNames, firstWord == "Oops" message = TRUE)                                                                                               
# DESCRIPTION: Takes the column names of a data frame and checks to make sure whatever "choice" you made (be it 
# your choice of dummies or your choice of chops) is actually in the data frame columns. Makes troubleshooting easier. 
# This function is also important in prechecking names to make sure the formula ends up being right. Use it after 
# adding in new data to check the "choose" options. Set firstWord to the first word you want said before an exclamation point.
# The warn argument (previously message) can be set to TRUE if you only want to 
#####

CheckChoice <- function(names, dataNames, firstWord = "Oops", warn = FALSE) {

  for (name in names) {

    if (warn == TRUE) { if(!(name %in% dataNames)) { warning(paste0(firstWord, "! The column/value/argument, ", name, ", was not valid OR not in your data! Check your input! This is a warning message of that!")) } }
    if (warn == FALSE) { if(!(name %in% dataNames)) { stop(paste0(firstWord, "! The column/value/argument, " , name, ", was not valid OR not in your data! Check your input!")) } }

  }
}

2
0

Ответ #10

Ответ на вопрос: Добавить (вставить) столбец между двумя столбцами в data.frame

Я бы просто использовал для этого cbind():

> df <- data.frame(a=1:5,
+                  b=10:14,
+                  c=rep(0,5),
+                  d=7:11)
> 
> z <- LETTERS[1:5]
> df <- cbind(df[,1:2], z, df[,3:4]) # Puts the z column between 2nd and 3rd column of df
> df
  a  b z c  d
1 1 10 A 0  7
2 2 11 B 0  8
3 3 12 C 0  9
4 4 13 D 0 10
5 5 14 E 0 11

9X_r-language

2
0

Ответ #11

Ответ на вопрос: Добавить (вставить) столбец между двумя столбцами в data.frame

Эта функция вставляет один нулевой столбец 9X_insert между всеми существующими столбцами во фрейме 9X_data.frame данных.

insertaCols<-function(dad){   
  nueva<-as.data.frame(matrix(rep(0,nrow(daf)*ncol(daf)*2 ),ncol=ncol(daf)*2))  
   for(k in 1:ncol(daf)){   
      nueva[,(k*2)-1]=daf[,k]   
      colnames(nueva)[(k*2)-1]=colnames(daf)[k]  
      }  
   return(nueva)   
  }

1
0

Ответ #12

Ответ на вопрос: Добавить (вставить) столбец между двумя столбцами в data.frame

Вот пример того, как переместить столбец 9X_data-frame с последней позиции на первую. Он объединяет 9X_dataframes [ с ncol. Я подумал, что было бы полезно получить 9X_r здесь очень короткий ответ для занятого 9X_r-df читателя:

d = mtcars
d[, c(ncol(d), 1:(ncol(d)-1))] 

1
0

Ответ #13

Ответ на вопрос: Добавить (вставить) столбец между двумя столбцами в data.frame

Вы можете использовать функцию append() для вставки 9X_insert элементов в векторы или списки (фреймы данных 9X_r-df - это списки). Просто:

df <- data.frame(a=c(1,2), b=c(3,4), c=c(5,6))

df <- as.data.frame(append(df, list(d=df$b+df$c), after=2))

Или, если вы хотите 9X_insert указать позицию по имени, используйте which:

df <- as.data.frame(append(df, list(d=df$b+df$c), after=which(names(df)=="b")))

1
0