programing

data.frame의 두 열 사이에 열을 추가(삽입)합니다.

starjava 2023. 6. 11. 10:13
반응형

data.frame의 두 열 사이에 열을 추가(삽입)합니다.

저는 열이 a, b, c인 데이터 프레임을 가지고 있습니다.저는 b와 c 사이에 새로운 d열을 추가하고 싶습니다.

cbind를 사용하여 마지막에 추가할 수 있다는 것을 알고 있습니다만, 두 열 사이에 삽입하려면 어떻게 해야 합니까?

저는 당신이 그 기능을 사용하는 것을 제안하고 싶습니다.add_column()포장에서.

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

열 인덱스 대신 열 이름을 사용할 수 있습니다.

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

또는 인수를 사용.before대신에.after형편이 좋으시다면

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

새 열에 추가:

df$d <- list/data

그러면 당신은 그것들을 다시 주문할 수 있습니다.

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

[을(를) 사용하여 열 순서를 변경하거나 원하는 순서대로 열을 표시할 수 있습니다.

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

라고 가정하면c항상 바로 뒤에 옵니다.b이 코드는 다음 뒤에 열을 추가합니다.b어디에 있든b데이터 프레임에 있습니다.

> 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

아니면 더 자연스럽게:

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

예제 data.frame을 만들고 여기에 열을 추가합니다.

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)]]

또는 열 이름별로

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

열 x와 y로 정의된 이전 데이터 프레임(old.df)에 열 z를 추가하려고 합니다.

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

new.df라는 새 데이터 프레임을 정의합니다.

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

데이터 프레임의 특정 위치에 열을 삽입하는 빠르고 더러운 방법은 다음과 같습니다.이 경우 원래 데이터 프레임에 5개의 열이 있습니다.c1, c2, c3, c4, c5새 열을 삽입합니다.c2b사이에c2그리고.c3.

먼저 테스트 데이터 프레임을 생성합니다.

> 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

새 열 추가c2b데이터 프레임의 끝에서:

> 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

열 인덱스를 기준으로 데이터 프레임 순서를 변경합니다.이 경우 기존 2열과 3열 사이에 새 열(6)을 삽입하려고 합니다.벡터를 사용하여 데이터 프레임의 열 주소를 지정합니다.c(1:2, 6, 3:5)와 동등한.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

저기야!

쉬운 해결책.5개의 열이 있는 데이터 프레임에서 3과 4 사이에 다른 열을 삽입하려면...

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

이를 위해 다음과 같은 기능을 작성했습니다.

[계속]


이제 이 기능을 업데이트했습니다.before그리고.after기능 및 기본값placeto 1. 데이터 테이블 호환성도 제공합니다.

#####
# 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)

}

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!")) } }

  }
}

저는 간단히 사용할 것입니다.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

이 함수는 데이터 프레임에 있는 모든 기존 열 사이에 0 열을 하나 삽입합니다.

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)   
  }

다음은 마지막 위치에서 첫 번째 위치로 열을 이동하는 방법의 예입니다.결합합니다.[와 함께ncol저는 바쁜 독자들을 위해 여기에 매우 짧은 대답을 하는 것이 유용할 것이라고 생각했습니다.

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

당신은 할 수 .append()벡터 또는 목록에 항목을 삽입하는 기능(데이터 프레임은 목록임).단순:

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))

하려면 또는이위지정하면려치를을 합니다.which:

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

`

data1 <- data.frame(col1=1:4, col2=5:8, col3=9:12)
row.names(data1) <- c("row1","row2","row3","row4")
data1
data2 <- data.frame(col1=21:24, col2=25:28, col3=29:32)
row.names(data2) <- c("row1","row2","row3","row4")
data2
insertPosition = 2
leftBlock <- unlist(data1[,1:(insertPosition-1)])
insertBlock <- unlist(data2[,1:length(data2[1,])])
rightBlock <- unlist(data1[,insertPosition:length(data1[1,])])
newData <- matrix(c(leftBlock, insertBlock, rightBlock), nrow=length(data1[,1]), byrow=FALSE)
newData

`

R에는 새 열을 추가할 위치를 지정하는 기능이 없습니다.예.,mtcars$mycol<-'foo'항상 마지막 열로 추가됩니다. 수단 다른수사예용단예(용사:▁(단)을 사용하는 :dplyr's select() 위치로 할 수 mycol을 사용합니다.이것은 이상적이지 않으며 R은 나중에 이를 변경하려고 할 수도 있습니다.

당신은 아래와 같이 할 수 있습니다.

df <- data.frame(a=1:4, b=5:8, c=9:12)
df['d'] <- seq(10,13)
df <- df[,c('a','b','d','c')]
df <- data.frame(a=c(1,2), b=c(3,4), c=c(5,6))
df %>%
  mutate(d= a/2) %>%
  select(a, b, d, c)

결과.

  a b   d c
1 1 3 0.5 5
2 2 4 1.0 6

를 사용할 것을 제안합니다.dplyr::select나고끝 dplyr::mutate열의 하위 집합을 선택/선택 취소할 수 있는 많은 도우미가 있습니다.

이 질문의 맥락에서 선택한 순서는 출력 data.frame에 반영됩니다.

열을 할 수 때.b 앞에 c사용할 수 있습니다.match의 열 , 둘다의열찾으면려를호,min 열 와 아쪽열번얻고를호래를 seq_len이 열까지 시퀀스를 가져옵니다.그런 다음 새 열을 배치하는 대신 이 인덱스를 의 부분 집합으로 사용할 수 있습니다.d그런 다음 시퀀스를 의 부분 집합으로 다시 사용합니다.

i <- seq_len(min(match(c("b", "c"), colnames(x))))
data.frame(x[i], d, x[-i])
#cbind(x[i], d, x[-i]) #Alternative
#  a b  d c
#1 1 4 10 7
#2 2 5 11 8
#3 3 6 12 9

이 그 요.b 앞에 c 열을 할 수 .d나고끝 b:

i <- seq_len(match("b", colnames(x)))
data.frame(x[i], d, x[-i])
#  a b  d c
#1 1 4 10 7
#2 2 5 11 8
#3 3 6 12 9

데이터:

x <- data.frame(a = 1:3, b = 4:6, c = 7:9)
d <- 10:12

언급URL : https://stackoverflow.com/questions/13502601/add-insert-a-column-between-two-columns-in-a-data-frame

반응형