如何使用toString创建字符串?
我有一个包含两列的数据表:category和priority。我使用for循环按以下方式对数据进行分类:如何使用toString创建字符串?,r,data.table,tostring,R,Data.table,Tostring,我有一个包含两列的数据表:category和priority。我使用for循环按以下方式对数据进行分类: 我检查实际值的优先级是否小于 上一个 我将category的值保存在“new”列中 我将category的上一个值保存在列上的字符串中 “rest” 如果实际值的优先级更高,我会执行相反的操作 手术 我已经尝试了函数paste、paste0和toString,但没有达到预期的效果 priority您很接近,只需添加1:x序列(表示为#)而不是单个值 data.dt$new <- N
- 我检查实际值的优先级是否小于 上一个
- 我将category的值保存在“
”列中new
- 我将category的上一个值保存在列上的字符串中
“
”rest
- 如果实际值的优先级更高,我会执行相反的操作 手术
paste
、paste0
和toString
,但没有达到预期的效果
priority您很接近,只需添加1:x
序列(表示为#
)而不是单个值
data.dt$new <- NA
data.dt$rest <- NA
for (i in 2:nrow(data.dt)) {
if(data.dt$priority[i] <= data.dt$priority[i-1]) {
data.dt$new[[i]] <- data.dt$category[i]
data.dt$rest[[i]] <- toString(data.dt$category[1:(i-1)]) #
}
else{
data.dt$new[[i]] <- data.dt$category[i-1]
data.dt$rest[[i]] <- toString(data.dt$category[1:i]) #
}
}
# priority category new rest
# 1: 3 a <NA> <NA>
# 2: 2 b b a
# 3: 1 c c a, b
# 4: 4 d c a, b, c, d
# 5: 5 e d a, b, c, d, e
# 6: 6 f e a, b, c, d, e, f
# 7: 7 g f a, b, c, d, e, f, g
说明:diff
计算每个值与其上一个值的差值;我们在diff
为<0
的条件下应用ifelse
(如果if
和else
,则将其矢量化)
sl <- c(NA, Map(function(x) toString(data.dt$category[seq(x)]), seq(nrow(data.dt))))
data.dt$rest <- ifelse(c(NA, diff(data.dt$priority)) < 0, sl, sl[-1])
data.dt
# priority category new rest
# 1: 3 a <NA> NA
# 2: 2 b b a
# 3: 1 c c a, b
# 4: 4 d c a, b, c, d
# 5: 5 e d a, b, c, d, e
# 6: 6 f e a, b, c, d, e, f
# 7: 7 g f a, b, c, d, e, f, g
说明:对于rest
列,我们希望seq
uencessc
具有我们使用Map
实现的实际行长度。因为我们不希望这些值已经出现在new
列中,所以在应用toString
之前,我们将sc
与数据.dt$new
匹配。unlist
为我们提供了一个向量,因为我们不需要类列表的列
查看?Map
显示它以相同的顺序将FUN
操作依次应用于以下两个对象:Map(FUN,x,y)
。结果收集在一个列表中。对于第四个元素,如下所示:
# Map(FUN, x, y)
(x <- sc[[4]])
# [1] "a" "b" "c" "d"
(y <- data.dt$new[[4]])
# [1] "c"
toString(x[is.na(match(x, y))]) # FUN
# [1] "a, b, d"
#地图(趣味、x、y)
(x感谢@jay.sf!!代码的第二部分是什么?@Ipa非常欢迎,也可以查看更新!您可能指的是数据部分,它旨在让其他用户快速复制运行代码所需的数据。如果我想在“rest”上删除“new”值,每行中的列,我应该在de代码中添加什么?@Ipa请参见upate!谢谢@jay.sf!!它可以工作!可以使用“gsub()”来完成吗?
sc <- Map(function(x) c(data.dt$category[seq(x)]), seq(nrow(data.dt)))
data.dt$rest <- unlist(c(NA, Map(function(x, y)
toString(x[is.na(match(x, y))]), sc, data.dt$new)[-1]))
# Map(FUN, x, y)
(x <- sc[[4]])
# [1] "a" "b" "c" "d"
(y <- data.dt$new[[4]])
# [1] "c"
toString(x[is.na(match(x, y))]) # FUN
# [1] "a, b, d"
data.dt
# priority category new rest
# 1 3 a <NA> <NA>
# 2 2 b b a
# 3 1 c c a, b
# 4 4 d c a, b, d
# 5 5 e d a, b, c, e
# 6 6 f e a, b, c, d, f
# 7 7 g f a, b, c, d, e, g
data.dt <- structure(list(priority = c(3, 2, 1, 4, 5, 6, 7), category = c("a",
"b", "c", "d", "e", "f", "g")), row.names = c(NA, -7L), class = c("data.table",
"data.frame"))