【问题标题】:For loop with an index inside a string in RFor循环在R中的字符串内具有索引
【发布时间】:2018-08-13 07:06:32
【问题描述】:

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

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

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

【问题讨论】:

  • 与stringr 你可以做data$indice &lt;- str_extract(data$cycle, "\\d")

标签: r string for-loop indexing


【解决方案1】:

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

【讨论】:

    【解决方案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
    

    【讨论】:

    • 如果重点是获取元素的实际索引值(基于它在向量中的位置)并将其用作行名,请不要这样做:) 如果重点是提取字符串的一部分,那么这是一个很好的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-17
    • 2021-12-18
    • 2021-12-08
    • 2022-09-29
    • 2021-07-07
    • 1970-01-01
    相关资源
    最近更新 更多