sourcecode

dplyr:: 하나의 열을 선택하고 벡터로 출력

copyscript 2023. 9. 11. 21:58
반응형

dplyr:: 하나의 열을 선택하고 벡터로 출력

dplyr::select결과는 data.frame, 결과가 하나의 열일 경우 벡터를 반환하도록 만드는 방법이 있습니까?

지금은 한단계 더 해야합니다 (res <- res$ydata.frame에서 벡터로 변환하려면 다음 예를 참조하십시오.

#dummy data
df <- data.frame(x = 1:10, y = LETTERS[1:10], stringsAsFactors = FALSE)

#dplyr filter and select results in data.frame
res <- df %>% filter(x > 5) %>% select(y)
class(res)
#[1] "data.frame"

#desired result is a character vector
res <- res$y
class(res)
#[1] "character"

아래와 같은 것:

res <- df %>% filter(x > 5) %>% select(y) %>% as.character
res
# This gives strange output
[1] "c(\"F\", \"G\", \"H\", \"I\", \"J\")"

# I need:
# [1] "F" "G" "H" "I" "J"

가장 좋은 방법(IMO):

library(dplyr)
df <- data_frame(x = 1:10, y = LETTERS[1:10])

df %>% 
  filter(x > 5) %>% 
  .$y

이제 dplyr 0.7.0에서 pull()을 사용할 수 있습니다.

df %>% filter(x > 5) %>% pull(y)

이런 거?

> res <- df %>% filter(x>5) %>% select(y) %>% sapply(as.character) %>% as.vector
> res
[1] "F" "G" "H" "I" "J"
> class(res)
[1] "character"

당신도 시도해 볼 수 있습니다.

res <- df %>%
           filter(x>5) %>%
           select(y) %>%
           as.matrix() %>%
           c()
#[1] "F" "G" "H" "I" "J"

 class(res)
#[1] "character"

언급URL : https://stackoverflow.com/questions/27149306/dplyrselect-one-column-and-output-as-vector

반응형