apply over matrix by column - any way to get column name?
One common way to deal with this is to loop over the column names themselves:
m <- matrix(runif(16),4,4)
colnames(m) <- letters[1:4]
sapply(colnames(m),function(x){mean(m[,x])})
a b c d
0.4720319 0.4992337 0.5026318 0.3514267
Extract matrix column values by matrix column name
Yes. But place your "test" after the comma if you want the column...
> A <- matrix(sample(1:12,12,T),ncol=4)
> rownames(A) <- letters[1:3]
> colnames(A) <- letters[11:14]
> A[,"l"]
a b c
6 10 1
see also help(Extract)
Extract column names for each value in column in matrix in R
We may use paste
in a vectorized way by rep
licating the column names with col
index and then get the unique
after paste
ing with the values of the n.mat
(it is a data.frame
after as.data.frame
- so we used unlist
)
unique(paste(colnames(n.mat)[col(n.mat)], unlist(n.mat), sep="_"))
-output
[1] "V1_M" "V1_F" "V2_A" "V2_B" "V3_T" "V3_G" "V3_H" "V4_D"
[9] "V4_G" "V5_T" "V5_X" "V6_Y" "V6_J"
Or if need a loop, use Map
unlist(Map(function(x, y) unique(paste(y, x, sep = "_")),
unname(n.mat), names(n.mat)))
The apply
wouldn't work here as the names
for each column will be the row.names attribute (even if change the OP's code to names
)
Get column names from a matrix using a condition
If it is really a matrix
and not a data.frame
then:
colnames(your_matrix)
Gives the column names - a character vector.
Since price is in the first row
your_matrix[1, ] > 20000
Gives a logical vector indicating the columns where the price is greater than 20000.
To get "column names from the cars that their price is bigger than 20000", just put those pieces together, using the logical test you want to subset the column names vector.
colnames(your_matrix)[your_matrix[1, ] > 20000]
Colnames passed through an apply function R
Thanks to the commentors I arrived at the below which give me my desired result.
trialData <- data.frame('a' = rnorm(100),
'b' = rnorm(100),
'c' = rnorm(100))
someData <- function(dataInput){
# lots of code here
return(
dataName = colnames(dataInput)
)
}
dataOutput <- lapply(colnames(trialData), function(x){someData(trialData[x])})
print(dataOutput)
How do I retrieve a matrix column and row name by a matrix index value?
First you need to get the row and column of that index using arrayInd
.
k <- arrayInd(4, dim(mdat))
You can then get the right name by getting that element of the row and column names
rownames(mdat)[k[,1]]
colnames(mdat)[k[,2]]
Or both at once using mapply
:
mapply(`[[`, dimnames(mdat), k)
Returning Column Name from Matrix based on value in R
1
Run sapply
over columns and find min
and then check if the min
meets your condition.
colnames(DF)[sapply(DF, min) <= 2]
#[1] "V3"
2
You can also run apply
on columns (MARGIN = 2
) to see if any
value in each column meets the required condition
colnames(DF)[apply(DF, MARGIN = 2, function(a) any(a<=2))]
#[1] "V3"
3
Use arr.ind = TRUE
with which
. This will give the indices of the values that meet the condition of which
. From that, extract the column information [,2]
.
unique(colnames(DF)[which(DF<=2, arr.ind = TRUE)[,2]])
#[1] "V3"
DATA
set.seed(42)
DF <- matrix(sample(1:9,9),ncol=3,nrow=3)
DF <- as.data.frame.matrix(DF)
DF
# V1 V2 V3
#1 9 5 6
#2 8 4 1
#3 3 7 2
Keep column name when select one column from a data frame/matrix in R
Use the drop
argument:
> x <- matrix(1,3,3)
> colnames(x) <- c("test1","test2","test3")
> x[,1, drop = FALSE]
test1
[1,] 1
[2,] 1
[3,] 1
Print column name in an r apply and save as new column on a dataframe
I think a lot of people will look for this same issue, so I'm answering my own question (having eventually found the answers). As below, there are other answers to both parts (thanks!) but non-combining these issues (and some of the examples are more complex).
First, it seems the "colnames" element really isn't something you can get around (seems weird to me!), so you 'loop' over the column names, and within the function call the actual vectors by name [c(x)].
Then the key thing is that to assign, so create your new columns, within an apply, you use '<<'
apply(colnames(df[c("a","b","c")]),function(x) {
z <- (ChISEQCIS[c(paste0(x))]/ChISEQCIS[c("V1")])
ChISEQCIS[c(paste0(x,"ind"))] <<- z
}
)
The << is discussed e.g. https://stackoverflow.com/questions/2628621/how-do-you-use-scoping-assignment-in-r
I got confused because I only vaguely thought about wanting to save the outputs initially and I figured I needed both the column (I incorrectly assumed apply worked like a loop so I could use a counter as an index or something) and that there should be same way to get the name separately (e.g. colname(x)).
There are a couple of related stack questions:
- https://stackoverflow.com/questions/9624866/access-to-column-name-of-dataframe-with-apply-function
- https://stackoverflow.com/questions/21512041/printing-a-column-name-inside-lapply-function
- https://stackoverflow.com/questions/10956873/how-to-print-the-name-of-current-row-when-using-apply-in-r
- https://stackoverflow.com/questions/7681013/apply-over-matrix-by-column-any-way-to-get-column-name (easiest to understand)
Related Topics
Add One Column Below Another in a Data.Frame in R
How to Add an External Legend to Ggpairs()
R: Why Does Read.Table Stop Reading a File
Add Textbox to Facet Wrapped Layout in Ggplot2
R Dplyr Join by Range or Virtual Column
Dodging Points and Error Bars with Ggplot
R Shiny Error: Cannot Coerce Type 'Closure' to Vector of Type 'Double'
Convert Column in Data.Frame to Date
Coding Variable Values into Classes Using R
Plot Mean and Sd of Dataset Per X Value Using Ggplot2
Shiny: How to Adjust the Width of the Tabsetpanel
Dynamically Add Function to R6 Class Instance
How to Create Design Matrix in R
Adding Text to Ggplot Geom_Jitter Points That Match a Condition
How to Plot the Relative Proportions of Two Groups Using a Fill Aesthetic in Ggplot2