问题描述
我正在清理一个大型数据集,并在from tkinter import *
from tkinter.ttk import ComboBox
root = Tk()
def log_last():
global last,cur
last = cur
cur = tx.get()
def append_tx(event):
if last:
v = last.split(",")
else:
v = []
v = list(filter(None,v))
if cur in v:
v.remove(cur)
else:
v.append(cur)
tx.set(",".join(v))
combo.selection_clear()
combo.icursor("end")
last,cur = "",""
tx = StringVar()
combo = ComboBox(root,textvariable=tx,values=list(range(10)))
combo.pack()
combo.bind("<<ComboBoxSelected>>",append_tx)
tx.trace("w",lambda a,b,c: log_last())
root.mainloop()
列中评论了对数据所做的更改。我在下面提供了一个虚拟样本集,作为我要实现的目标的示例。我正在使用Comments
包。
数据:
tidyverse
我希望将文本添加到与structure(list(Date = structure(c(17199,17226,17263,17300,17346,17504,17508),class = "Date"),Skipper = c("Agatha","Gertrude","Julio","Dylis","Agatha","Julio"),Success = c("No","Yes","No","No"),Time = c(60L,50L,120L,30L,100L,40L),Comments = c("Pirates spotted.","Illegal fishers spotted.","Engine troubles.","Lost fishing line.",NA,"Pirates spotted.","Lost fishing line.")),class = "data.frame",row.names = c(NA,-7L))
相关的Comments
的字符串值中,而不删除已经存在的值。
因此对于Date
和2017-04-07
,我想在受尊敬的2017-12-04
的{{1}}上添加Iceberg spotted.
。
Comments
使用Date
和 Date Skipper Success Time Comments
1 2017-02-02 Agatha No 60 Pirates spotted.
2 2017-03-01 Gertrude Yes 50 Illegal fishers spotted.
3 2017-04-07 Julio Yes 120 Engine troubles.
4 2017-05-14 Dylis Yes 30 Lost fishing line.
5 2017-06-29 Agatha No 100 <NA>
6 2017-12-04 Dylis Yes 120 Pirates spotted.
7 2017-12-08 Julio No 40 Lost fishing line.
stringr
str_c
如何选择要应用上述^代码的日期,以便查看指定日期对数据集所做的更改。我是否需要提供R_example$Comments %>% str_c("Iceberg spotted")
或[1] "Pirates spotted.Iceberg spotted"
函数?
我一直在尝试使用filter
,但这将替换现有的值。我还可以通过创建另一个列,然后将两个列绑定在一起来做到这一点,但是我宁愿不这样做。
if_else
谢谢。
编辑:
我忘记了数据集中的一些细节。如果我有多个行用于钓鱼,并且在case_when
列的R_example %>%
mutate(Comments = case_when(Date == "2017-04-07" & Date == "2017-12-04" ~ "Iceberg spotted.",TRUE ~ as.character(Comments)))
值中,该字符串如何替换Comments
的值而不是添加到<NA>
的值?像这样:
我的数据如下:
<NA>
我想要实现的目标:
<NA>
我目前从以下答案中的代码中得到什么:
Date Skipper Success Time Comments
1 2017-02-02 Agatha No 60 Pirates spotted.
2 2017-02-02 Agatha No 60 <NA>
解决方法
在这种情况下,我会使用ifelse
dta %>%
mutate(
Comments = if_else(Date %in% c(as.Date("2017-04-07"),as.Date("2017-12-04")),paste0(Comments,"Iceberg spotted"),Comments)
)
,
以R为底的解决方案:
# Find which rows will be changed
i <- which(df$Date %in% c(as.Date("2017-04-07"),as.Date("2017-12-04")))
# Modify the rows accordingly
df[i,"Comments"] <- paste(df[i,"Comments"],"Iceberg Spotted.")
结果:
> df
Date Skipper Success Time Comments
1 2017-02-02 Agatha No 60 Pirates spotted.
2 2017-03-01 Gertrude Yes 50 Illegal fishers spotted.
3 2017-04-07 Julio Yes 120 Engine troubles. Iceberg Spotted.
4 2017-05-14 Dylis Yes 30 Lost fishing line.
5 2017-06-29 Agatha No 100 <NA>
6 2017-12-04 Dylis Yes 120 Pirates spotted. Iceberg Spotted.
7 2017-12-08 Julio No 40 Lost fishing line.