access data frame column using variable
After creating your data frame, you need to use ?colnames. For example, you would have:
d = data.frame(a=c(1,2,3), b=c(4,5,6))
colnames(d) <- c("col1", "col2")
You can also name your variables when you create the data frame. For example:
d = data.frame(col1=c(1,2,3), col2=c(4,5,6))
Further, if you have the names of columns stored in variables, as in
a <- "col1"
you can't use $
to select a column via d$a
. R will look for a column whose name is a
. Instead, you can do either d[[a]]
or d[,a]
.
Dynamically select data frame columns using $ and a character value
You can't do that kind of subsetting with $
. In the source code (R/src/main/subset.c
) it states:
/*The $ subset operator.
We need to be sure to only evaluate the first argument.
The second will be a symbol that needs to be matched, not evaluated.
*/
Second argument? What?! You have to realise that $
, like everything else in R, (including for instance (
, +
, ^
etc) is a function, that takes arguments and is evaluated. df$V1
could be rewritten as
`$`(df , V1)
or indeed
`$`(df , "V1")
But...
`$`(df , paste0("V1") )
...for instance will never work, nor will anything else that must first be evaluated in the second argument. You may only pass a string which is never evaluated.
Instead use [
(or [[
if you want to extract only a single column as a vector).
For example,
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]
You can perform the ordering without loops, using do.call
to construct the call to order
. Here is a reproducible example below:
# 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
Access column using variable name in R in if statement, condition has length 1
The way you're selecting columns in fine. Using df[[col_name]]
(list context) is the same as df[, col_name]
-- each returns a vector copy of column col_name
. You can save the column name as a variable instead of using paste0
directly in the selection.
The reason you're getting an error is that if
is not vectorized and you're giving it a vector with length > 1. In this case, if
uses only the first value in the vector, but warns that it's doing so. ifelse
is the vectorized version in base R (there's also dplyr::if_else
). If I understand your code, the below should be close to what you're looking for.
t1 <- paste0('Z_in_', trait1)
t2 <- paste0('Z_in_', trait2)
# a single boolean vector indicating if trait1 and trait2 are
# both positive or both negative
same_sign <- ((leadsnp4[, t1] > 0) & (leadsnp4[, t2] > 0)) |
((leadsnp4[, t1] < 0) & (leadsnp4[, t2] < 0))
leadsnp4$ConcordEffect <- ifelse(same_sign, "Yes", "No")
Note that if trait1
and/or trai2
are equal to 0 they will be assigned false
. You'll need to modify the logic if this is not the desired behavior.
How to use a string variable to select a data frame column using $ notation
If you have a variable x
with a column name in tmp
, tmp[,x]
or tmp[[x]]
are the correct ways to extract it. You cannot get R to treat tmp$x
as tmp$"Q5.3"
. tmp$x
will always refer to the item named "x" in "tmp".
How to access the name of a column which is a number through a variable
You can simply do-
> k=99
> df[[paste0(k)]]
[1] 1 2 3
Just for more clarification on your for loop
-
cols <- c(99,66)
for(i in 1:length(cols))
{
print(df[[paste0(cols[i])]])
}
Output-
[1] 1 2 3
[1] 4 5 6
Select columns using a variable in R
We can use ..
before the idx to select the columns in data.table
or with = FALSE
library(data.table)
df[, ..idx]
df[, idx, with = FALSE]
How can I Access a Column by Name as a Variable to use the isin() Method
Give this a try.. using the set functionality
Usercol ='Account' #user entry
Common =
list(set(df1.loc[:Usercol]).intersect(set(df2.loc[:Usercol])))
#fetch index of each data frame using
df1[df1[Usercol].isin(Common)].index
df2[df2[Usercol].isin(Common)].index
using a variable to specify a column in a dataframe
If we want to use an object, then use [[
instead of $
similar to the 'zonename'
mean(zones[[zonename]][[atr]] , na.rm = TRUE) #
Related Topics
R - Waiting for Page to Load in Rselenium with Phantomjs
How to Speed Up R Packages Installation in Docker
How to Calculate the Area of Polygon Overlap in R
Frequency Table with Several Variables in R
Ggplot2 Multiline Title, Different Indentations
Specifying the Scale for the Density in Ggplot2's Stat_Density2D
How to Turn the Numeric Output of Boxplot (With Plot=False) into Something Usable
R: Replace Na with Item from Vector
Split a Vector into Three Vectors of Unequal Length in R
Plotting Continuous and Discrete Series in Ggplot with Facet
R: Merge Based on Multiple Conditions (With Non-Equal Criteria)
Keep Same Order as in Data Files When Using Ggplot
Plotting Functions on Top of Datapoints in R
Stacked Histograms Like in Flow Cytometry
Write a Data Frame to CSV File Without Column Header in R
How to Skip Error Checking at Rmarkdown Compiling