对于在R中的字符串内具有索引的循环

时间:2021-01-22 20:15:44

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?

所以我有一个列循环的数据集,其中包含行cycle1,cycle2,cycle3。我想替换例如单词cycle1只有数字1.如何以某种方式将索引i与字符串循环分开?

for (i in 1:3){
   data$cycle[data$cycle=="cyclei"]<-i
}

2 个解决方案

#1


2  

Replace "cycle" with the empty string and convert to numeric:

用空字符串替换“cycle”并转换为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

#2


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 #

#1


2  

Replace "cycle" with the empty string and convert to numeric:

用空字符串替换“cycle”并转换为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

#2


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 #