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

时间:2018-03-05 15:17:27

标签: r string for-loop indexing

我有一个相当简单的问题,但不知怎的,我无法解决它。

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

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

2 个答案:

答案 0 :(得分:2)

"cycle"替换为空字符串并转换为数字:

data <- data.frame(cycle = c("cycle2", "cycle1", "cycle3")) # sample input

transform(data, cycle = as.numeric(sub("cycle", "", cycle)))

,并提供:

  cycle
1     2
2     1
3     3

答案 1 :(得分:2)

使用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 #