1

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
}
1
  • with stringr you can do data$indice <- str_extract(data$cycle, "\\d") Commented Mar 5, 2018 at 15:22

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

if the point is to get the actual index value of the element (based on its position in the vector) and use that for the row name, please don't do it this way :) If the point is to extract a portion of the string, then this is a good answer.
2

Use 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 #

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.