对于R gsub()中字符串内的索引的循环

问题描述 投票:0回答:2

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

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

for (i in 1:3){
   data$cycle[data$cycle=="cyclei"]<-i
}
r string for-loop indexing
2个回答
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

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 #
© www.soinside.com 2019 - 2024. All rights reserved.