Reputation: 793
I have a csv file ss1.csv that looks like this:
dput(ss1)
structure(list(IDs = structure(1:10, .Label = c("1", "2", "3",
"4", "5", "6", "7", "8", "9", "10"), class = "factor"), n1 = c("2",
"1", "1", "1", "3", "2", "4", "5", "7", "6"), n2 = c("3", "4",
"4", "2", "4", "4", "5", "7", "8", "7"), n3 = c("4", "6", "5",
"3", "7", "7", "6", "9", "10", "9"), n4 = c(NA, NA, NA, "5",
"8", "10", "8", NA, NA, NA), n5 = c(NA, NA, NA, "6", NA, NA,
"9", NA, NA, NA), n6 = c(NA, NA, NA, "7", NA, NA, "10", NA, NA,
NA)), row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame"
))
I want to replace all the values in columns n1...nn by values in a txt file. The txt file (Map.txt) looks like this:
1 => 10
2 => 20
3 => 30
4 => 40
5 => 50
6 => 60
7 => 70
8 => 80
9 => 90
10 => 100
At the moment I am going this and its working:
sed `cat Map.txt | awk '{print "-e s/"$1"/"$3"/"}'`<<< "`cat ss1.csv`" > results.csv
But I want to find a way to do this in R. Hope someone can help! Thanks
Upvotes: 1
Views: 53
Reputation: 887851
We could multiply by 10 after converting to integer
library(dplyr)
ss1 <- ss1 %>%
mutate_at(vars(-IDs), ~ as.integer(.) * 10)
Or if we want to generalize, use a named vector
nm1 <- setNames(seq(10, 100, by = 10), 1:10)
ss1 %>%
mutate_at(vars(-IDs), ~ nm1[.])
If we want to use Map.txt
df1 <- read.table(text = paste(sub("\\s*=>\\s*", " ",
readLines('Map.txt')), collapse="\n"), header = FALSE)
nm1 <- setNames(df1$V2, df1$V1)
and use that in mutate_at
Or in base R
ss1[-1] <- as.integer(as.matrix(ss1[-1])) * 10
Upvotes: 1