Get the vector of values from different columns of a matrix
This should do it for you:
M.mat[cbind(seq_along(Idx),Idx)]
Get different columns of each row from matrix
Since you want row-major order (and Matlab works in column major order), transpose A
first. Then build a logical mask to be used as index into A
transposed:
At = A.'; %'
mask = (bsxfun(@ge, (1:size(At,1)), B(:,1)) & bsxfun(@le, 1:size(At,1), B(:,2))).'; %'
result = At(mask);
How to select elements of a matrix given a vector with same number of columns?
We can construct a matrix
of row/column indexes to extract. The column sequence can be seq_len(ncol
mat1[cbind(vec1, seq_len(ncol(mat1)))]
[1] 13 6 19 4
Or another option is to extract the rows
and use diag
diag(mat1[vec1,])
[1] 13 6 19 4
Using row-wise column indices in a vector to extract values from data frame
Just use matrix indexing, like this:
dframe[cbind(seq_along(i), i)]
# [1] "g" "b" "f"
The cbind(seq_along(i), i)
part creates a two column matrix of the relevant row and column that you want to extract.
Values from multiple dataframe columns into one vector
I've found that converting to a matrix first makes getting to levels a bit easier.
as.vector(as.matrix(df[,c("alpha", "gamma", "zeta")]))
Of course, you could have just done stringsAsFactors=FALSE
when you read the data in initially.
Subset a matrix according to a columns vector
Try
H[cbind(seq_len(nrow(H)), P)]
## [1] 0.6733731 0.7396847 0.5953580
Here we are indexing by consecutive rows and columns indicated in P
Regarding your question, so the reason H[, P]
returns a matrix is because you are telling R:
select all rows in columns: 2, 1, 2 from matrix "H"
thus the result that you are getting is a matrix with identical first and third columns.
In R, split vector valued column in data frame into multiple columns
In this case, with a matrix, you can use cbind
:
cbind(results[1], results[[2]])
# y 1 2 3
# 1 0 0.4710224 0.4280053 0.3206661
# 2 1 0.5769064 0.6220120 0.2683387
Using [
on the first argument makes sure it is a data.frame
, so cbind.data.frame
is used and the result is not coerced to matrix. But using [[
on the second argument makes sure that we are binding to the 2x3
matrix in the second column rather than a data frame containing that matrix.
More generally, tidyr::unnest
works well with vector
or list
columns, but the result is in long form - you would have to add a column id and spread it to get it back to wide form.
However, the simplest way may be to use dplyr
and summarize_at
with a custom .funs
argument:
library(dplyr)
descrip = funs(m = mean, med = median, sd = sd)
Df %>% group_by(y) %>% summarize_at("x", .funs = descrip)
# # A tibble: 2 × 4
# y m med sd
# <dbl> <dbl> <dbl> <dbl>
# 1 0 0.4710224 0.4280053 0.3206661
# 2 1 0.5769064 0.6220120 0.2683387
How to compare two columns of matrix in r and output the column name in a new vector
You need the vectorized version of if/else. The matrix version:
ifelse(data[,2] > data[,1], "second", "first")
Vectorizing a for loop that changes columns of a matrix
An alternative to the t(apply
in @Jon Spring's answer is matrixStats::rowCumsums
.
library(matrixStats)
n <- 1e4L
n10 <- n/10L
age.mat <- outer(sample(150, n, TRUE), seq(0, 20, 5), "+")
x.mat <- matrix(FALSE, n, 5) # create the empty harvest matrix
# sample harvests so that no tree is harvested twice
x.mat[matrix(c(sample(n, n/2L), sample(n10:(6L*n10 - 1L)) %/% n10), n/2L)] <- TRUE
f1 <- function(age, x) {
age[x[,1],] <- 0
for (i in 2:5){ # we don't need to calculate over the first year
age[,i] <- age[,i - 1] + 5L # add 5 to previous year
age[x[,i], i] <- 0L # reset age of harvested trees to zero
}
age
}
f2 <- function(age, x) {
age - rowCumsums(x*age)
}
microbenchmark::microbenchmark(f1 = f1(age.mat, x.mat),
f2 = f2(age.mat, x.mat),
check = "equal")
#> Unit: microseconds
#> expr min lq mean median uq max neval
#> f1 294.4 530.2 1023.450 566.6 629.35 33222.8 100
#> f2 135.2 263.6 334.622 284.2 307.15 4343.6 100
Tidyverse approach to selecting values from different columns in a dataframe with row-column index pairs
You could do
rain %>%
mutate(id = row_number()) %>%
pivot_longer(-id) %>%
inner_join(tibble(id = seq_along(v), name = v))
which returns
# A tibble: 5 x 3
id name value
<int> <chr> <dbl>
1 1 els 1
2 2 ceres 1
3 3 els 1
4 4 mond 0
5 5 ceres 3
Adding
pull(value, name)
returns the named vector
#> els ceres els mond ceres
#> 1 1 1 0 3
Related Topics
Iteratively Constructed Dataframe in R
How to Apply a Gradient Fill to a Geom_Rect Object in Ggplot2
Update Rows of Data Frame in R
How to Use Variables Newly Created in 'J' in the Same 'J' Argument
How to Use a Character Vector of Column Names in the Formula Argument of Dcast (Reshape2)
Error While Using Install_Github | Devtools | Timeout Issue
Quickest Way to Read a Subset of Rows of a CSV
Change All Columns from Factor to Numeric in R
How to Create an Infix %Between% Operator
Order Categorical Data in a Stacked Bar Plot with Ggplot2
Shiny Dashboard Mainpanel Height Issue
R: Why Kable Doesn't Print Inside a for Loop
Filling Bars in Barplot with Textiles in Ggplot2
Cbind Two Lists of Data.Frames to a New List