$ 및 문자 값을 사용하여 데이터 프레임 열을 동적으로 선택 데이터 세트 mtcars와 문자형 벡터에 저장된 일부

다른 열 이름의 벡터가 있고 각 열을 반복하여 data.frame에서 해당 열을 추출 할 수 있기를 원합니다. 예를 들어, 데이터 세트 mtcars와 문자형 벡터에 저장된 일부 변수 이름을 고려하십시오 cols. mtcars의 동적 하위 집합을 사용하여 변수를 선택하려고하면 cols이러한 작업의 아래에

cols <- c("mpg", "cyl", "am")
col <- cols[1]
col
# [1] "mpg"

mtcars$col
# NULL
mtcars$cols[1]
# NULL

어떻게 이것들이 같은 값을 반환하도록 할 수 있습니까?

mtcars$mpg

또한 cols어떤 종류의 루프에서 값을 얻기 위해 모든 열을 어떻게 반복 할 수 있습니까?

for(x in seq_along(cols)) {
   value <- mtcars[ order(mtcars$cols[x]), ]
}



답변

당신은 그런 종류의 부분 집합을 할 수 없습니다 $. 소스 코드 ( R/src/main/subset.c)에서 다음과 같이 설명합니다.

/ * $ 하위 집합 연산자.
우리는 첫 번째 주장 만 평가해야합니다.
두 번째는 평가되지 않고 일치해야하는 기호입니다.
* /

두 번째 논쟁? 뭐?! 당신은 그 실현이 $R에서 다른 모든 것들처럼, (예를 들면 포함, (, +, ^인수를 평가하는 기능이며, 등). df$V1다음과 같이 다시 작성할 수 있습니다.

`$`(df , V1)

또는 실제로

`$`(df , "V1")

그러나…

`$`(df , paste0("V1") )

… 예를 들어 결코 작동하지 않을 것이며 두 번째 인수에서 먼저 평가되어야하는 다른 어떤 것도 작동하지 않을 것입니다. 평가 되지 않는 문자열 만 전달할 수 있습니다 .

대신 사용하십시오 [(또는 [[단일 열만 벡터로 추출하려는 경우).

예를 들면

var <- "mpg"
#Doesn't work
mtcars$var
#These both work, but note that what they return is different
# the first is a vector, the second is a data.frame
mtcars[[var]]
mtcars[var]

를 사용하여 do.call에 대한 호출을 생성 하여 루프없이 순서를 수행 할 수 있습니다 order. 다음은 재현 가능한 예입니다.

#  set seed for reproducibility
set.seed(123)
df <- data.frame( col1 = sample(5,10,repl=T) , col2 = sample(5,10,repl=T) , col3 = sample(5,10,repl=T) )

#  We want to sort by 'col3' then by 'col1'
sort_list <- c("col3","col1")

#  Use 'do.call' to call order. Seccond argument in do.call is a list of arguments
#  to pass to the first argument, in this case 'order'.
#  Since  a data.frame is really a list, we just subset the data.frame
#  according to the columns we want to sort in, in that order
df[ do.call( order , df[ , match( sort_list , names(df) ) ]  ) , ]

   col1 col2 col3
10    3    5    1
9     3    2    2
7     3    2    3
8     5    1    3
6     1    5    4
3     3    4    4
2     4    3    4
5     5    1    4
1     2    5    5
4     5    3    5


답변

내가 올바르게 이해한다면 변수 이름을 포함하는 벡터가 있으며 각 이름을 반복하고 데이터 프레임을 정렬하고 싶습니다. 그렇다면이 예제는 해결책을 보여줄 것입니다. 귀하의 주요 문제 (전체 예제가 완전하지 않아서 무엇을 놓치고 있는지 잘 모르겠습니다)는 매개 변수가 직접 열과 반대되는 변수 이름을 포함하는 외부 객체이기 때문에 order(Q1_R1000[,parameter[X]])대신 이어야한다는 것입니다 order(Q1_R1000$parameter[X]). 데이터 프레임의 ( $적절한 경우).

set.seed(1)
dat <- data.frame(var1=round(rnorm(10)),
                   var2=round(rnorm(10)),
                   var3=round(rnorm(10)))
param <- paste0("var",1:3)
dat
#   var1 var2 var3
#1    -1    2    1
#2     0    0    1
#3    -1   -1    0
#4     2   -2   -2
#5     0    1    1
#6    -1    0    0
#7     0    0    0
#8     1    1   -1
#9     1    1    0
#10    0    1    0

for(p in rev(param)){
   dat <- dat[order(dat[,p]),]
 }
dat
#   var1 var2 var3
#3    -1   -1    0
#6    -1    0    0
#1    -1    2    1
#7     0    0    0
#2     0    0    1
#10    0    1    0
#5     0    1    1
#8     1    1   -1
#9     1    1    0
#4     2   -2   -2


답변

dplyr을 사용하면 데이터 프레임을 정렬하기위한 쉬운 구문이 제공됩니다.

library(dplyr)
mtcars %>% arrange(gear, desc(mpg))

여기표시된대로 NSE 버전을 사용 하여 정렬 목록을 동적으로 작성 하는 것이 유용 할 수 있습니다.

sort_list <- c("gear", "desc(mpg)")
mtcars %>% arrange_(.dots = sort_list)


답변

또 다른 해결책은 #get을 사용하는 것입니다.

> cols <- c("cyl", "am")
> get(cols[1], mtcars)
 [1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8 4


답변

동일한 열에 대해 다양한 이름을 가진 일부 CSV 파일로 인해 유사한 문제가 발생했습니다.
이것이 해결책이었습니다.

목록에서 첫 번째 유효한 열 이름을 반환하는 함수를 작성한 다음 사용했습니다.

# Return the string name of the first name in names that is a column name in tbl
# else null
ChooseCorrectColumnName <- function(tbl, names) {
for(n in names) {
    if (n %in% colnames(tbl)) {
        return(n)
    }
}
return(null)
}

then...

cptcodefieldname = ChooseCorrectColumnName(file, c("CPT", "CPT.Code"))
icdcodefieldname = ChooseCorrectColumnName(file, c("ICD.10.CM.Code", "ICD10.Code"))

if (is.null(cptcodefieldname) || is.null(icdcodefieldname)) {
        print("Bad file column name")
}

# Here we use the hash table implementation where 
# we have a string key and list value so we need actual strings,
# not Factors
file[cptcodefieldname] = as.character(file[cptcodefieldname])
file[icdcodefieldname] = as.character(file[icdcodefieldname])
for (i in 1:length(file[cptcodefieldname])) {
    cpt_valid_icds[file[cptcodefieldname][i]] <<- unique(c(cpt_valid_icds[[file[cptcodefieldname][i]]], file[icdcodefieldname][i]))
}


답변

특정 이름을 가진 열을 선택하려면 다음을 수행하십시오.

A=mtcars[,which(conames(mtcars)==cols[1])]
#and then
colnames(mtcars)[A]=cols[1]

예를 들어 A가 데이터 프레임이고 xyz가 x로 명명되는 열인 경우 동적 이름을 추가하는 방법을 반대로 수행 할 수도 있습니다.

A$tmp=xyz
colnames(A)[colnames(A)=="tmp"]=x

다시 이것은 루프에 추가 할 수도 있습니다.


답변

mtcars[do.call(order, mtcars[cols]), ]