为什么从数据帧中提取日期在函数外部时有效,而在函数内部使用时无效?R



我对一般的编码很陌生,感觉这个问题更多的是结构问题,而不是语法问题。

我有以下数据帧:

mm <- c(0,0,1,30,0,50)
dates <- as.Date(c("2020-06-01", "2020-06-02", "2020-06-03", "2020-06-04", "2020-06-05", "2020-06-06"))
weather <- data.frame(dates, mm)

如果给定日期的降雨量为35毫米或更大,我想创建一个函数和循环来连接字符串和日期。

testfunction <- function() {
if(i >= 35) {
print(paste(c(
"here's the date:", 
weather$dates[weather$mm>=35]),
sep = " "))
}}
for (i in weather$mm) {
testfunction()}

现在,如果我在函数之外单独运行日期提取行:

weather$dates[weather$mm>=35]
> "2020-06-06"

但当我在循环中运行它时:

> "here's the date:" "18419"  

忽略预期的字符串输出,为什么日期提取不返回与函数外相同的内容?

只是"dates"列的Date类被强制为integer值,而它与character矢量连接(c(

paste(c(
"here's the date:", weather$dates))
#[1] "here's the date:" "18414"            "18415"            "18416"            "18417"            "18418"            "18419"

我们可以通过使用as.character转换为character来避免这种情况

paste(c(
"here's the date:", as.character(weather$dates)))

功能可以更改为

testfunction <- function() {
if(i >= 35) {
print(paste(c(
"here's the date:", 
as.character(weather$dates)[weather$mm>=35]),
sep = " "))
}}

然后应用

for (i in weather$mm) {
testfunction()}

-输出

[1] "here's the date:" "2020-06-06"      

此外,还不完全清楚为什么需要连接(如注释中所示(。如果目的是创建一个字符串(目前,它返回多个字符串作为串联的一部分(,我们可以使用paste作为

paste("here's the date: ", weather$dates[weather$mm>=35])

如果我们需要在下一行打印,请使用cat,而paste则使用sep的元素作为n

testfunction <- function() {
if(i >= 35) {
cat(paste(
"here's the date:", 
weather$dates[weather$mm>=35],
sep = "n"), "n")
}}
for (i in weather$mm) {
testfunction()}
#here's the date:
#2020-06-06 
mm <- c(0,0,1,30,0,50)
dates <- as.character(c("2020-06-01", "2020-06-02", "2020-06-03", "2020-06-04", "2020-06-05", "2020-06-06"))
weather <- data.frame(dates, mm)
testfunction <- function(x) {
if(x >= 35) {
print(paste(c(
"here's the date:", 
weather$dates[weather$mm>=35]),
sep = " "))
}}
for (i in weather$mm) {
testfunction(i)
}
#> [1] "here's the date:" "2020-06-06"

创建于2021-06-01由reprex包(v2.0.0(

最新更新