Reputation: 61
I have a rather simple problem but somehow I cannot solve it.
So I have a dataset with a column cycle with rows cycle1, cycle2, cycle3. I want to replace e.g. the word cycle1 with just the number 1. How to somehow separate the index i from the string cycle?
for (i in 1:3){
data$cycle[data$cycle=="cyclei"]<-i
}
Upvotes: 1
Views: 567
Reputation: 2920
gsub()
# load data
df <- data.frame( cycle = c( "cycle1", "cycle2", "cycle3" ), stringsAsFactors = FALSE )
# Identify the pattern and replace with nothing
# and cast the values as numeric
df$cycle <- as.numeric( gsub( pattern = "cycle", replacement = "", x = df$cycle ) )
# view results
df
# cycle
# 1 1
# 2 2
# 3 3
# end of script #
Upvotes: 2
Reputation: 269596
Replace "cycle"
with the empty string and convert to numeric:
data <- data.frame(cycle = c("cycle2", "cycle1", "cycle3")) # sample input
transform(data, cycle = as.numeric(sub("cycle", "", cycle)))
giving:
cycle
1 2
2 1
3 3
Upvotes: 2