Hello everyone out here! I have a 63x6 matrix mat (Columns: x-coordinates, y-coordinates, value_1,value_2, etc). The value_1 should be written into a 7x9 matrix according to its coordinates given. This solution doesn't work: (like many others I've tried..)
for (r in 1:nrow(df)) {
for (c in 1:ncol(df)) {
df[r,c] <- mat$value_1[mat$x == c && mat$y == r]
}
}
Could anyone help? Thanks!
@Mael: I dont know if you meant it that way:
NMIN_struct <-
structure(
list(
x = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 1),
y = c(1,
1, 1, 1, 1, 1, 1, 1, 1, 2),
Sample_ID = c(1, 1, 1, 2, 2, 2, 3,
3, 3, 4),
Nmin1 = c(
11.1788110878291,
11.1788110878291,
11.1788110878291,
5.17227718787078,
5.17227718787078,
5.17227718787078,
5.39282332521486,
5.39282332521486,
5.39282332521486,
2.76320633985937
),
Nmin2 = c(
2.16160208812242,
2.16160208812242,
2.16160208812242,
1.89355337232599,
1.89355337232599,
1.89355337232599,
1.82901181814765,
1.82901181814765,
1.82901181814765,
1.37989208438326
),
Nmin3 = c(
1.01043537292747,
1.01043537292747,
1.01043537292747,
1.05972539906962,
1.05972539906962,
1.05972539906962,
0.901859608440133,
0.901859608440133,
0.901859608440133,
0.710021005623553
)
),
row.names = c(NA,-10L),
class = c("tbl_df", "tbl", "data.frame")
)
CodePudding user response:
The base [
primitive accepts a 2-column matrix as an argument, where column 1 identifies rows and column 2 identifies columns. For instance, using a contrived matrix re-assigning 4 values in mtcars
:
mat <- data.frame(row=c(1:3,3), col=c(2,3,1,3), val=90000:90003)
head(mtcars)
# mpg cyl disp hp drat wt qsec vs am gear carb
# Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
# Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
# Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
# Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
# Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
# Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
mtcars[ as.matrix(mat[,c("row","col")]) ] <- mat$val
head(mtcars)
# mpg cyl disp hp drat wt qsec vs am gear carb
# Mazda RX4 21.0 90000 160 110 3.90 2.620 16.46 0 1 4 4
# Mazda RX4 Wag 21.0 6 90001 110 3.90 2.875 17.02 0 1 4 4
# Datsun 710 90002.0 4 90003 93 3.85 2.320 18.61 1 1 4 1
# Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
# Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
# Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
(This works on frames and matrices alike.)