programing

data.table의 열 클래스 변환

copyandpastes 2023. 6. 15. 22:51
반응형

data.table의 열 클래스 변환

data.table을 사용하는 데 문제가 있습니다.열 클래스를 변환하려면 어떻게 해야 합니까?다음은 간단한 예입니다.data.frame을 사용하면 변환하는 데 문제가 없습니다. data.table을 사용하면 다음과 같은 방법을 알 수 없습니다.

df <- data.frame(ID=c(rep("A", 5), rep("B",5)), Quarter=c(1:5, 1:5), value=rnorm(10))
#One way: http://stackoverflow.com/questions/2851015/r-convert-data-frame-columns-from-factors-to-characters
df <- data.frame(lapply(df, as.character), stringsAsFactors=FALSE)
#Another way
df[, "value"] <- as.numeric(df[, "value"])

library(data.table)
dt <- data.table(ID=c(rep("A", 5), rep("B",5)), Quarter=c(1:5, 1:5), value=rnorm(10))
dt <- data.table(lapply(dt, as.character), stringsAsFactors=FALSE) 
#Error in rep("", ncol(xi)) : invalid 'times' argument
#Produces error, does data.table not have the option stringsAsFactors?
dt[, "ID", with=FALSE] <- as.character(dt[, "ID", with=FALSE]) 
#Produces error: Error in `[<-.data.table`(`*tmp*`, , "ID", with = FALSE, value = "c(1, 1, 1, 1, 1, 2, 2, 2, 2, 2)") : 
#unused argument(s) (with = FALSE)

제가 여기서 명백한 것을 놓치나요?

매튜의 게시물로 인한 업데이트:이전에 이전 버전을 사용했지만 1.6.6(현재 사용하는 버전)으로 업데이트한 후에도 여전히 오류가 발생합니다.

업데이트 2: 클래스 "요인"의 모든 열을 "문자" 열로 변환하고 싶지만 어떤 열이 어떤 클래스의 열인지 미리 모른다고 가정해 보겠습니다.data.frame을 사용하면 다음 작업을 수행할 수 있습니다.

classes <- as.character(sapply(df, class))
colClasses <- which(classes=="factor")
df[, colClasses] <- sapply(df[, colClasses], as.character)

data.table과 비슷한 것을 할 수 있습니까?

업데이트 3:

sessionInfo() R 버전 2.13.1(2011-07-08) 플랫폼: x86_64-pc-mingw32/x64(64비트)

locale:
[1] C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] data.table_1.6.6

loaded via a namespace (and not attached):
[1] tools_2.13.1

단일 열의 경우:

dtnew <- dt[, Quarter:=as.character(Quarter)]
str(dtnew)

Classes ‘data.table’ and 'data.frame':  10 obs. of  3 variables:
 $ ID     : Factor w/ 2 levels "A","B": 1 1 1 1 1 2 2 2 2 2
 $ Quarter: chr  "1" "2" "3" "4" ...
 $ value  : num  -0.838 0.146 -1.059 -1.197 0.282 ...

사용.lapply그리고.as.character:

dtnew <- dt[, lapply(.SD, as.character), by=ID]
str(dtnew)

Classes ‘data.table’ and 'data.frame':  10 obs. of  3 variables:
 $ ID     : Factor w/ 2 levels "A","B": 1 1 1 1 1 2 2 2 2 2
 $ Quarter: chr  "1" "2" "3" "4" ...
 $ value  : chr  "1.487145280568" "-0.827845218358881" "0.028977182770002" "1.35392750102305" ...

사용해 보세요.

DT <- data.table(X1 = c("a", "b"), X2 = c(1,2), X3 = c("hello", "you"))
changeCols <- colnames(DT)[which(as.vector(DT[,lapply(.SD, class)]) == "character")]

DT[,(changeCols):= lapply(.SD, as.factor), .SDcols = changeCols]

Genorama의 답변에 대한 Matt Dowle의 논평을 제기하는 것(https://stackoverflow.com/a/20808945/4241780) 은 더 명확하게 하기 위해 (격려받은 대로), 당신은 다음을 사용할 수 있습니다.for(...)set(...).


library(data.table)

DT = data.table(a = LETTERS[c(3L,1:3)], b = 4:7, c = letters[1:4])
DT1 <- copy(DT)
names_factors <- c("a", "c")

for(col in names_factors)
  set(DT, j = col, value = as.factor(DT[[col]]))

sapply(DT, class)
#>         a         b         c 
#>  "factor" "integer"  "factor"

reprex 패키지(v0.3.0)에 의해 2020-02-12에 생성되었습니다.

자세한 내용은 https://stackoverflow.com/a/33000778/4241780 에서 Matt의 다른 의견을 참조하십시오.

편집.

에스펜과 에 의해 언급된 바와 같이.help(set),j열 이름(문자) 또는 열이 이미 존재하는 경우 값을 할당할 숫자(정수)일 수 있습니다.그렇게names_factors <- c(1L, 3L)또한 작동할 것입니다.

이것은 그것을 하는 나쁜 방법입니다!다른 이상한 문제가 해결될 경우에만 이 답변을 남깁니다.이러한 더 나은 방법은 부분적으로 최신 데이터의 결과일 수 있습니다. 테이블 버전...그래서 이 어려운 방법을 기록할 가치가 있습니다.또한 이것은 다음을 위한 좋은 구문 예제입니다.eval substitute통사론

library(data.table)
dt <- data.table(ID = c(rep("A", 5), rep("B",5)), 
                 fac1 = c(1:5, 1:5), 
                 fac2 = c(1:5, 1:5) * 2, 
                 val1 = rnorm(10),
                 val2 = rnorm(10))

names_factors = c('fac1', 'fac2')
names_values = c('val1', 'val2')

for (col in names_factors){
  e = substitute(X := as.factor(X), list(X = as.symbol(col)))
  dt[ , eval(e)]
}
for (col in names_values){
  e = substitute(X := as.numeric(X), list(X = as.symbol(col)))
  dt[ , eval(e)]
}

str(dt)

당신에게 주는 것은

Classes ‘data.table’ and 'data.frame':  10 obs. of  5 variables:
 $ ID  : chr  "A" "A" "A" "A" ...
 $ fac1: Factor w/ 5 levels "1","2","3","4",..: 1 2 3 4 5 1 2 3 4 5
 $ fac2: Factor w/ 5 levels "2","4","6","8",..: 1 2 3 4 5 1 2 3 4 5
 $ val1: num  0.0459 2.0113 0.5186 -0.8348 -0.2185 ...
 $ val2: num  -0.0688 0.6544 0.267 -0.1322 -0.4893 ...
 - attr(*, ".internal.selfref")=<externalptr> 

data.table에 열 이름 목록이 있는 경우 다음 작업관리 클래스를 변경할 수 있습니다.

convert_to_character <- c("Quarter", "value")

dt[, convert_to_character] <- dt[, lapply(.SD, as.character), .SDcols = convert_to_character]

저는 몇 가지 접근법을 시도했습니다.

# BY {dplyr}
data.table(ID      = c(rep("A", 5), rep("B",5)), 
           Quarter = c(1:5, 1:5), 
           value   = rnorm(10)) -> df1
df1 %<>% dplyr::mutate(ID      = as.factor(ID),
                       Quarter = as.character(Quarter))
# check classes
dplyr::glimpse(df1)
# Observations: 10
# Variables: 3
# $ ID      (fctr) A, A, A, A, A, B, B, B, B, B
# $ Quarter (chr) "1", "2", "3", "4", "5", "1", "2", "3", "4", "5"
# $ value   (dbl) -0.07676732, 0.25376110, 2.47192852, 0.84929175, -0.13567312,  -0.94224435, 0.80213218, -0.89652819...

그렇지 않으면

# from list to data.table using data.table::setDT
list(ID      = as.factor(c(rep("A", 5), rep("B",5))), 
     Quarter = as.character(c(1:5, 1:5)), 
     value   = rnorm(10)) %>% setDT(list.df) -> df2
class(df2)
# [1] "data.table" "data.frame"

더 일반적이고 안전한 방법을 제공합니다

".." <- function (x) 
{
  stopifnot(inherits(x, "character"))
  stopifnot(length(x) == 1)
  get(x, parent.frame(4))
}


set_colclass <- function(x, class){
  stopifnot(all(class %in% c("integer", "numeric", "double","factor","character")))
  for(i in intersect(names(class), names(x))){
    f <- get(paste0("as.", class[i]))
    x[, (..("i")):=..("f")(get(..("i")))]
  }
  invisible(x)
}

함수..변수를 data.table 범위에서 벗어나게 합니다. set_colclass는 콜의 클래스를 설정합니다.다음과 같이 사용할 수 있습니다.

dt <- data.table(i=1:3,f=3:1)
set_colclass(dt, c(i="character"))
class(dt$i)

@Nera가 제안한 것과 동일한 방법으로 수업을 먼저 확인하되 사용하는 대신.SD데이터의 빠른 루프를 사용하는 것입니다. 테이블과set클래스 검사가 추가된 @Matt Dowle 솔루션입니다.

for (j in seq_len(ncol(DT))){
  if(class(DT[[j]]) == 'factor')
    set(DT, j = j, value = as.character(DT[[j]]))
}
columnID = c(1,2) # or
columnID = c('column1','column2')


for(i in columnID) class(dt[[i]]) <- 'character'

루프의 경우 열 벡터의 특성을 문자 클래스로 변경합니다.실제로는 data.table을 목록 유형으로 처리합니다.

시도:

dt <- data.table(A = c(1:5), 
                 B= c(11:15))

x <- ncol(dt)

for(i in 1:x) 
{
     dt[[i]] <- as.character(dt[[i]])
}

언급URL : https://stackoverflow.com/questions/7813578/convert-column-classes-in-data-table

반응형