Reputation: 2310
I would like to replace a string (number '2' in my example) in a data-frame differently based on the row number. This is my input:
df <- "2 2 2 3
3 3 2 1"
df <- read.table(text=df)
This would be my expected output:
dfout <- "1R 1R 1R 3
3 3 2R 1"
dfout <- read.table(text=df)
Therefore, the number '2' should be replace by '1R' in the first row, by '2R' in the second row and so on in larger matrices (my real data has more than 1000 rows). I tried the below code without success:
apply(g1x, 1, function(x) gsub("2", nrow(x), x))
I would be glad for any help here.
Upvotes: 0
Views: 117
Reputation: 38500
Here is as base R method using which
with the arr.ind argument. It is similar in spirit to thelatemail's method.
pos <- which(df == 2, arr.ind=TRUE)
df[pos] <- paste0(pos[,1], "R")
this returns
df
V1 V2 V3 V4
1 1R 1R 1R 3
2 3 3 2R 1
Upvotes: 1
Reputation: 51592
Here is an idea using sapply
from base R,
as.data.frame(t(sapply(seq(nrow(df)), function(i)
replace(df[i,], df[i,] == 2, paste0(i, 'R')))))
which gives,
V1 V2 V3 V4 1 1R 1R 1R 3 2 3 3 2R 1
Upvotes: 3
Reputation: 577
Using data.table
library(data.table)
df <- "2 2 2 3
3 3 2 1"
df <- data.table(read.table(text=df))
mycols <- names(df)
df[, (mycols) := lapply(.SD, function(x) ifelse(x==2, paste0(df[,.I], "R"),x)), .SDcols = mycols]
Upvotes: 0
Reputation: 93813
A variation on @sotos' answer:
replace(df, df==2, paste0(row(df)[df==2], "R")
# V1 V2 V3 V4
#1 1R 1R 1R 3
#2 3 3 2R 1
Equivalent to the replacement form of:
df[df==2] <- paste0(row(df)[df==2], "R")
Upvotes: 4