I have the following data frame (data) from which I will like to extract and print column headers where ever there is a non-zero element:
M1 M2 M3 M4
2 0 1 0 1
5 1 -1 0 0
7 0 1 1 0
Required output:
2: M2 M4
5: M1 M2
7: M2 M3
So far my R code is not working:
colnames(data)[which(data[2] !=0),]
Help will be appreciated. Thanks
Just click the Navigation Pane button under Kutools Tab, and it displays the Navigation pane at the left. Under the Column Tab, it lists all column header names. Note:It will locate a cell containing column header name as soon as possible if you click the column name in the navigation pane.
Use list(df) to Get Column Names from DataFrame. Use list(df) to get the column header from pandas DataFrame. You can also use list(df. columns) to get column names.
To extract columns with a particular string in column name of an R data frame, we can use grepl function for column names and then subset the data frame with single square brackets.
USE db_name; DESCRIBE table_name; it'll give you column names with the type.
This will always return a list:
Map(`[`, list(names(df)), split(col(df)[df != 0],
row(df)[df != 0]))
# [[1]]
# [1] "M2" "M4"
#
# [[2]]
# [1] "M1" "M2"
#
# [[3]]
# [1] "M2" "M3"
(And you can wrap in inside setNames(..., rownames(df))
if you want the list to share df
's row names.)
Let's take the more general case of irregular results:
dat <- structure(list(M1 = c(0L, 1L, 0L), M2 = c(1L, -1L, 1L), M3 = -1:1,
M4 = c(1L, 0L, 0L)), .Names = c("M1", "M2", "M3", "M4"),
class = "data.frame", row.names = c("2", "5", "7"))
> dat
M1 M2 M3 M4
2 0 1 -1 1
5 1 -1 0 0
7 0 1 1 0
The inner apply "loop" constructs a logical set of vectors. Because R is column oriented the second level of processing is done on columns. The outer apply "loop" extracts the appropriate items from colnames:
apply( apply(dat,1, as.logical) , 2, function(ll) colnames(dat)[ll] )
$`2`
[1] "M2" "M3" "M4"
$`5`
[1] "M1" "M2"
$`7`
[1] "M2" "M3"
You could also have extracted the array indicator version of which() and then process the results:
> which(dat != 0, arr.ind=TRUE)
row col
5 2 1
2 1 2
5 2 2
7 3 2
2 1 3
7 3 3
2 1 4
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