[英]How to replace values in the columns of a dataframe based on the values in the other column in R?
[英]Selecting columns in R dataframe based on values of column in other dataframe
我有兩個數據框,如下所示。
#Dataframe 1
colname value
col1 0.45
col2 -0.2
col3 -0.4
col4 0.1
#Dataframe 2
col1 col2 col3 col4
1 5 9 5
45 29 43 9
34 33 56 3
2 67 76 1
我想要做的是首先選擇數據框 1 的所有列,其值 > 0.3 或值 < -0.3。 我想要的第二件事是從數據框 2 中選擇與此條件匹配的所有列。 所以應該將 dataframe2 的 col1 和 col3 列選擇到一個新的數據幀中,如下所示。
col1 col3
1 9
45 43
34 56
2 76
我想到的解決方案是首先選擇相關列,如下面的代碼所示。
library(sqldf)
features = sqldf('select colname from dataframe1 where value > 0.3 or value < -0.3')
在此之后,在 for 循環中構建一個字符串,如下所示。 並將其粘貼到sqldf
查詢中以從sqldf
中選擇正確的列。 但是我不知道如何構建這個字符串。 你們知道這個或有其他解決方案嗎?
stringValue = "col1, col3, col4"
sprintf("SELECT %s FROM dataframe2", stringValue)
使用您當前的dataframe1
只會選擇col1
和col3
。
library(sqldf)
features = sqldf('select colname from dataframe1 where value > 0.3 or value < -0.3')
sqldf(sprintf("SELECT %s FROM dataframe2", paste0(features$colname, collapse = ", ")))
# col1 col3
# 1 1 9
# 2 45 43
# 3 34 56
# 4 2 76
數據
#Dataframe 1
dataframe1 <- read.table(text = 'colname value
col1 0.45
col2 -0.2
col3 -0.4
col4 0.1', header = T, sep = "")
#Dataframe 2
dataframe2 <- read.table(text = 'col1 col2 col3 col4
1 5 9 5
45 29 43 9
34 33 56 3
2 67 76 1', header = T, sep = "")
這樣做的基本 R 方式:
> mask <- dataframe1$value > 0.3 | dataframe1$value < -0.3
> dataframe2[, mask]
col1 col3
1 1 9
2 45 43
3 34 56
4 2 76
使用dplyr
(不確定它是否相關),您可以執行以下操作:
df2 %>%
select(one_of(df1 %>% filter(value > 0.3 | value < -0.3) %>% pull(colname) %>% as.character()))
這是通過從df1
中選擇與one_of
字符串匹配的列名稱來工作的,該列名稱在filter
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.