amplify cells if numeric if the first date column at specific date range using R
时间: 2023-11-26 21:05:09 浏览: 62
R语言 处理日期数据
To amplify cells in R if numeric in the first date column at a specific date range, you can use the following code:
```r
# Here is an example dataframe
df <- data.frame(Date = seq(as.Date("2022/01/01"), by = "day", length.out = 10),
Col1 = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
Col2 = c(11, 12, 13, 14, 15, 16, 17, 18, 19, 20))
# Define the date range
start_date <- as.Date("2022-01-03")
end_date <- as.Date("2022-01-06")
# Amplify the cells if they meet the criteria
df[, 2:ncol(df)] <- apply(df[, 2:ncol(df)], 2, function(x) {
if (is.numeric(x) & names(df)[which(colnames(df) == names(x))] == "Date") {
ifelse(df$Date >= start_date & df$Date <= end_date, x * 2, x)
} else {
x
}
})
```
This code will check if the column is numeric and if it is the first column (named "Date"). Then, it will check if the value in the "Date" column falls within the specified date range. If it does, it will multiply the value by 2, otherwise, it will leave the value as is. The `apply()` function is used to loop through all columns in the dataframe except the first column (since it has already been checked).
阅读全文