Nice programing

string 형 벡터를 할당하여 열 이름으로 빈 데이터 프레임을 만드시겠습니까?

nicepro 2020. 12. 6. 22:06
반응형

string 형 벡터를 할당하여 열 이름으로 빈 데이터 프레임을 만드시겠습니까?


이 질문에 이미 답변이 있습니다.

1. 빈 데이터 프레임 생성

y <- data.frame()

2. string 형 벡터 x를 y에 열 이름으로 할당

x <- c("name", "age", "gender")
colnames(y) <- x

결과:

Error in `colnames<-`(`*tmp*`, value = c("name", "age", "gender")) : 
  'names' attribute [3] must be the same length as the vector [0]

실제로 x 길이는 동적이므로

y <- data.frame(name=character(), age=numeric(), gender=logical())

열 이름을 지정하는 효율적인 방법이 아닙니다. 문제를 어떻게 해결할 수 있습니까? 고마워


어때?

df <- data.frame(matrix(ncol = 3, nrow = 0))
x <- c("name", "age", "gender")
colnames(df) <- x

이 모든 작업을 한 줄로 수행하려면

setNames(data.frame(matrix(ncol = 3, nrow = 0)), c("name", "age", "gender"))

#[1] name   age    gender
#<0 rows> (or 0-length row.names)

참고 URL : https://stackoverflow.com/questions/32712301/create-empty-data-frame-with-column-names-by-assigning-a-string-vector

반응형