Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 205301

Selecting columns in R dataframe based on values of column in other dataframe

$
0
0

I have two dataframes as u can see below.

  #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

What I want to do is to firstly select all columns of dataframe 1 that have a value > 0.3 or value < -0.3. The second thing I want is to select all column from dataframe 2 that match this condition. So the columns col1, col3 and col4 of dataframe2 should be selected into a new dataframe like below.

col1  col3 col4
1     9    5
45    43   9
34    56   3
2     76   1

The solution I thought about is to firstly select the relevant columns as u can see in the code below.

library(sqldf)
features = sqldf('select colname from dataframe1 where value > 0.3 or value < -0.3')

After this to build a string in a for loop that should look like below. And paste this in a sqldf query to select to right columns from dataframe2. However I dont know how to build this string. U guys know this or have a other solution?

  stringValue = "col1, col3, col4"
   sprintf("SELECT %s FROM dataframe2", stringValue)

Viewing all articles
Browse latest Browse all 205301

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>