R How to Extract First Row of Each Matrix Within a List

R How do I extract first row of each matrix within a list?

Or,

lapply(mylist_1, `[`,1,)
lapply(mylist_1, `[`,2,)

Get access to the first row of a list in R

 A=list()
A[[1]]=c(1,2)
A[[2]]=c(3,4)
A[[3]]=c(5,6)

A
# [[1]]
# [1] 1 2

# [[2]]
# [1] 3 4

# [[3]]
# [1] 5 6

I. First Solution using sapply() function for just first elements

 sapply(A,'[[',1)
# [1] 1 3 5

For Getting lets say 1st, 3rd, 4th elements of each nested list. Not applicable in this example

 sapply(A,`[`,c(1,3,4))

II. Second Solution using for loop

 for(i in 1:length(A)){
print (A[[i]][1])
}
# [1] 1
# [1] 3
# [1] 5

Extract row from a matrix in a list in R

Or like this?

set.seed(123)
list1 <- list(replicate(4,rnorm(2)))
l<-rep(list1,3)
lapply(l,function(x) x[2,])

Select n first rows of a matrix

Use the head function:

head(mat, 100)

Extract the first TRUE per row in logical matrix efficiently in R

We can use max.col

colnames(m)[max.col(m, "first")]
#[1] "A" "B" "C" "B" "B" "A"

If there are no TRUE in a row, then we can change it to NA (if needed)

colnames(m)[max.col(m, "first")*NA^!rowSums(m)]

Or with ifelse

colnames(m)[ifelse(rowSums(m)==0, NA, max.col(m, "first"))]

extract one element/data frame from a list of lists

So after messing around, the answer seems to be very simple: `results1<-cj1["coefficients",]. This creates the list that I want. Akrun, if you read this, thank you for your support.

Select the first row by group

You can use duplicated to do this very quickly.

test[!duplicated(test$id),]

Benchmarks, for the speed freaks:

ju <- function() test[!duplicated(test$id),]
gs1 <- function() do.call(rbind, lapply(split(test, test$id), head, 1))
gs2 <- function() do.call(rbind, lapply(split(test, test$id), `[`, 1, ))
jply <- function() ddply(test,.(id),function(x) head(x,1))
jdt <- function() {
testd <- as.data.table(test)
setkey(testd,id)
# Initial solution (slow)
# testd[,lapply(.SD,function(x) head(x,1)),by = key(testd)]
# Faster options :
testd[!duplicated(id)] # (1)
# testd[, .SD[1L], by=key(testd)] # (2)
# testd[J(unique(id)),mult="first"] # (3)
# testd[ testd[,.I[1L],by=id] ] # (4) needs v1.8.3. Allows 2nd, 3rd etc
}

library(plyr)
library(data.table)
library(rbenchmark)

# sample data
set.seed(21)
test <- data.frame(id=sample(1e3, 1e5, TRUE), string=sample(LETTERS, 1e5, TRUE))
test <- test[order(test$id), ]

benchmark(ju(), gs1(), gs2(), jply(), jdt(),
replications=5, order="relative")[,1:6]
# test replications elapsed relative user.self sys.self
# 1 ju() 5 0.03 1.000 0.03 0.00
# 5 jdt() 5 0.03 1.000 0.03 0.00
# 3 gs2() 5 3.49 116.333 2.87 0.58
# 2 gs1() 5 3.58 119.333 3.00 0.58
# 4 jply() 5 3.69 123.000 3.11 0.51

Let's try that again, but with just the contenders from the first heat and with more data and more replications.

set.seed(21)
test <- data.frame(id=sample(1e4, 1e6, TRUE), string=sample(LETTERS, 1e6, TRUE))
test <- test[order(test$id), ]
benchmark(ju(), jdt(), order="relative")[,1:6]
# test replications elapsed relative user.self sys.self
# 1 ju() 100 5.48 1.000 4.44 1.00
# 2 jdt() 100 6.92 1.263 5.70 1.15

extract specific rows from nested lists of class dist in r

Here is an example using minimal sample data based on mtcars

lst <- lapply(1:3, function(x) dist(mtcars[, 1:3]))

We now extract the last row of every distance matrix from lst

lapply(lst, function(x) { mat <- as.matrix(x); mat[nrow(mat), ] })
#[[1]]
# Mazda RX4 Mazda RX4 Wag Datsun 710 Hornet 4 Drive
# 39.0532969 39.0532969 13.0751673 137.0145978
# Hornet Sportabout Valiant Duster 360 Merc 240D
# 239.0487189 104.0715619 239.1388927 25.8745048
# Merc 230 Merc 280 Merc 280C Merc 450SE
# 19.8494332 46.6947535 46.7816203 154.9323723
# Merc 450SL Merc 450SLC Cadillac Fleetwood Lincoln Continental
# 154.9059392 154.9757400 351.1951025 339.2020047
# Chrysler Imperial Fiat 128 Honda Civic Toyota Corolla
# 319.0954246 43.7068644 46.1853873 51.4418118
# Toyota Corona Dodge Challenger AMC Javelin Camaro Z28
# 0.9055385 197.1289172 183.1486828 229.1781185
# Pontiac Firebird Fiat X1-9 Porsche 914-2 Lotus Europa
# 279.0373452 42.4123803 4.6529560 27.4191539
# Ford Pantera L Ferrari Dino Maserati Bora Volvo 142E
# 230.1029335 24.1431150 180.1581527 0.0000000
#
#[[2]]
# Mazda RX4 Mazda RX4 Wag Datsun 710 Hornet 4 Drive
# 39.0532969 39.0532969 13.0751673 137.0145978
# Hornet Sportabout Valiant Duster 360 Merc 240D
# 239.0487189 104.0715619 239.1388927 25.8745048
# Merc 230 Merc 280 Merc 280C Merc 450SE
# 19.8494332 46.6947535 46.7816203 154.9323723
# Merc 450SL Merc 450SLC Cadillac Fleetwood Lincoln Continental
# 154.9059392 154.9757400 351.1951025 339.2020047
# Chrysler Imperial Fiat 128 Honda Civic Toyota Corolla
# 319.0954246 43.7068644 46.1853873 51.4418118
# Toyota Corona Dodge Challenger AMC Javelin Camaro Z28
# 0.9055385 197.1289172 183.1486828 229.1781185
# Pontiac Firebird Fiat X1-9 Porsche 914-2 Lotus Europa
# 279.0373452 42.4123803 4.6529560 27.4191539
# Ford Pantera L Ferrari Dino Maserati Bora Volvo 142E
# 230.1029335 24.1431150 180.1581527 0.0000000
#
#[[3]]
# Mazda RX4 Mazda RX4 Wag Datsun 710 Hornet 4 Drive
# 39.0532969 39.0532969 13.0751673 137.0145978
# Hornet Sportabout Valiant Duster 360 Merc 240D
# 239.0487189 104.0715619 239.1388927 25.8745048
# Merc 230 Merc 280 Merc 280C Merc 450SE
# 19.8494332 46.6947535 46.7816203 154.9323723
# Merc 450SL Merc 450SLC Cadillac Fleetwood Lincoln Continental
# 154.9059392 154.9757400 351.1951025 339.2020047
# Chrysler Imperial Fiat 128 Honda Civic Toyota Corolla
# 319.0954246 43.7068644 46.1853873 51.4418118
# Toyota Corona Dodge Challenger AMC Javelin Camaro Z28
# 0.9055385 197.1289172 183.1486828 229.1781185
# Pontiac Firebird Fiat X1-9 Porsche 914-2 Lotus Europa
# 279.0373452 42.4123803 4.6529560 27.4191539
# Ford Pantera L Ferrari Dino Maserati Bora Volvo 142E
# 230.1029335 24.1431150 180.1581527 0.0000000

Extract the first, second and last row that meets a criterion

Data table can help with this.
This is an edit off of Davids comment to move it into the answers as his approach is the correct way to do this.

library(data.table)
DT <- as.data.table(db)
DT[Weight >= 10][, .SD[c(1, 2, .N)], by = Class]

As as faster alternative also from David look at

 indx <- DT[Weight >= 10][, .I[c(1, 2, .N)], by = Class]$V1 ; DT[indx]

Which creates the wanted index using .I and then subsets DT based on those rows.



Related Topics



Leave a reply



Submit