This is probably much easier than I am making it. It is one of those little problems which hangs you up and you wonder why.
Given dataframe as so:
a <- c(1,2,3)
b <- c(4,5,6)
test.df <- data.frame(a,b)
How could one use iterate through the values in each column and return the column name and row name if the value = '1'?
Something like this:
for (i in test.df) {
for (j in i) {
if (i == 1) {
print(rowname,columnname)
}
}
}
}
Where rowname and columnname are actual values.
Method 1 : using rownames() A data frame's rows can be accessed using rownames() method in the R programming language. We can specify the new row names using a vector of numerical or strings and assign it back to the rownames() method.
To access a specific column in a dataframe by name, you use the $ operator in the form df$name where df is the name of the dataframe, and name is the name of the column you are interested in. This operation will then return the column you want as a vector.
Using which
and arr.ind=T
is a way:
Example Data
a <- c(1,2,3)
b <- c(4,5,6)
test.df <- data.frame(a,b)
Solution and Output
#test.df==1 gives a TRUE/FALSE matrix
#which with the arr.ind argument=TRUE gives the row/col of the TRUE elements
a <- which(test.df==1,arr.ind=T)
> a
row col
[1,] 1 1
And then you use the above to get the row and column names:
> row.names(test.df[a[,1],] ) #row names
[1] "1"
> names(test.df[a[,2]]) #column names
[1] "a"
Another approach:
> col = colnames(test.df)[apply(test.df, 2, function(u) any(u==1))]
> col
[1] "a"
> row = row.names(test.df)[apply(test.df, 1, function(u) any(u==1))]
> row
[1] "1"
This is an old thread but I am not very satisfied with the previous solutions.
For me the most intuitive is:
row.names(data)[which(data$feature1==value)]
Which is basically saying: Given the row names of all the data give me those where a given condition is satisfied.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With