programing

$ 및 문자 값을 사용하여 동적으로 데이터 프레임 열 선택

javajsp 2023. 6. 18. 12:10

$ 및 문자 값을 사용하여 동적으로 데이터 프레임 열 선택

다른 열 이름의 벡터를 가지고 있으며 각 열 이름을 루프하여 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

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

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

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

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

제가 올바르게 이해했다면, 변수 이름을 포함하는 벡터가 있고 각 이름을 반복하여 데이터 프레임을 정렬하고 싶습니다.그렇다면 이 예제에서는 솔루션을 설명해야 합니다.귀하의 주요 문제(전체 예제가 완료되지 않았기 때문에 "누락될 수 있는 것이 무엇인지 잘 모르겠다")는 것입니다.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

나는 그것을 구현할 것입니다.sym의 기능.rlang꾸러미예를 들어,col로서 가치가 있습니다."mpg"그 아이디어는 그것을 부분 집합화하는 것입니다.

mtcars %>% pull(!!sym(col))
#  [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2 10.4 10.4 14.7 32.4 30.4 33.9 21.5 15.5 15.2 13.3 19.2 27.3 26.0 30.4 15.8 19.7 15.0
# [32] 21.4

계속 코딩하기!

또 다른 해결책은 #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]))
}
mtcars[do.call(order, mtcars[cols]), ]

저한테 여러 번 있었어요.data.table 패키지를 사용합니다.참조해야 할 열이 하나만 있는 경우.둘 중 하나 사용

DT[[x]]

또는

DT[,..x]

참조할 열이 두 개 이상 있는 경우 다음을 사용해야 합니다.

DT[,..x]

이 x는 다른 data.frame의 문자열일 수 있습니다.

특정 이름을 가진 열을 선택하려면 다음을 수행합니다.

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

다시 말하지만 이것은 루프에도 추가될 수 있습니다.

너무 늦었습니다.하지만 제가 답을 가지고 있는 것 같아요.

여기 제 샘플 연구가 있습니다.df 데이터 프레임 -

   >study.df
   study   sample       collection_dt other_column
   1 DS-111 ES768098 2019-01-21:04:00:30         <NA>
   2 DS-111 ES768099 2018-12-20:08:00:30   some_value
   3 DS-111 ES768100                <NA>   some_value

그 다음엔...

> ## Selecting Columns in an Given order
> ## Create ColNames vector as per your Preference
> 
> selectCols <- c('study','collection_dt','sample')
> 
> ## Select data from Study.df with help of selection vector
> selectCols %>% select(.data=study.df,.)
   study       collection_dt   sample
1 DS-111 2019-01-21:04:00:30 ES768098
2 DS-111 2018-12-20:08:00:30 ES768099
3 DS-111                <NA> ES768100
> 

언급URL : https://stackoverflow.com/questions/18222286/dynamically-select-data-frame-columns-using-and-a-character-value