使用 tidyverse pivot_longer 时如何修改列中的数值(即乘以 10)
How do you modify numerical values from a column when using tidyverse pivot_longer (ie. multiplied by 10)
我需要用 B 变量值乘以 10 绘制以下图,以便调整到次轴。在 tidyverse
中如何做到这一点?我在 %>%
中使用 mutate 但不起作用
data<- data.frame(
Date=(1:13),
A=c(1.12,2.78,2.08,1.55,0.67,0.98,1.43,0.42,0.30,0.82,0.51,0.23,0.44),
B= c(0.10,0.07,0.04,0.05,0.10,0.08,0.12,0.05,0.02,0.11,0.06,0.05,0.11),
C= c(9.97,6.94,10.87,9.69,12.27,11.27,10.42,10.97,9.15,10.59,11.64,8.86,8.47))
library(tidyverse)
data %>%
select(-C) %>%
pivot_longer(cols = -Date) %>%
# mutate(data, B2= B*10) %>% THIS IS WHAT I AM TRYING AND DOES NOT WORK, B VALUE STO BE MULTIPLIED BY 10
ggplot(aes(Date, value, linetype = name)) +
geom_line() +
geom_point() +
scale_y_continuous(sec.axis = sec_axis(~./100, name= expression(paste("B", "(", mu, "M)")))) +
scale_linetype_manual(values= LINES) +
# scale_color_manual(name = "", values = c("A" = "black", "B" = "black"))+
theme_classic()+
ylab(bquote(A ~ (mu~M)))+
xlab("")
如果我理解正确的话,你想在 name == "B" 的情况下乘以 10。如果是这种情况,则可以使用 tidyverse:
data %>%
select(-C) %>%
pivot_longer(cols = -Date) %>%
mutate(value = case_when(name == "B" ~ value * 10, TRUE ~ value))
另一种选择是在 aes
中使用 ifelse
data %>%
select(-C) %>%
pivot_longer(cols = -Date) %>%
ggplot(aes(Date, ifelse(name == "B", 10 * value, value), linetype = name)) +
geom_line() +
geom_point() +
scale_y_continuous(sec.axis = sec_axis(~./100,
name= expression(paste("B", "(", mu, "M)")))) +
scale_linetype_manual(values = 1:2) +
theme_classic(base_size = 16) +
ylab(bquote(A ~ (mu~M))) +
xlab("")
我需要用 B 变量值乘以 10 绘制以下图,以便调整到次轴。在 tidyverse
中如何做到这一点?我在 %>%
中使用 mutate 但不起作用
data<- data.frame(
Date=(1:13),
A=c(1.12,2.78,2.08,1.55,0.67,0.98,1.43,0.42,0.30,0.82,0.51,0.23,0.44),
B= c(0.10,0.07,0.04,0.05,0.10,0.08,0.12,0.05,0.02,0.11,0.06,0.05,0.11),
C= c(9.97,6.94,10.87,9.69,12.27,11.27,10.42,10.97,9.15,10.59,11.64,8.86,8.47))
library(tidyverse)
data %>%
select(-C) %>%
pivot_longer(cols = -Date) %>%
# mutate(data, B2= B*10) %>% THIS IS WHAT I AM TRYING AND DOES NOT WORK, B VALUE STO BE MULTIPLIED BY 10
ggplot(aes(Date, value, linetype = name)) +
geom_line() +
geom_point() +
scale_y_continuous(sec.axis = sec_axis(~./100, name= expression(paste("B", "(", mu, "M)")))) +
scale_linetype_manual(values= LINES) +
# scale_color_manual(name = "", values = c("A" = "black", "B" = "black"))+
theme_classic()+
ylab(bquote(A ~ (mu~M)))+
xlab("")
如果我理解正确的话,你想在 name == "B" 的情况下乘以 10。如果是这种情况,则可以使用 tidyverse:
data %>%
select(-C) %>%
pivot_longer(cols = -Date) %>%
mutate(value = case_when(name == "B" ~ value * 10, TRUE ~ value))
另一种选择是在 aes
ifelse
data %>%
select(-C) %>%
pivot_longer(cols = -Date) %>%
ggplot(aes(Date, ifelse(name == "B", 10 * value, value), linetype = name)) +
geom_line() +
geom_point() +
scale_y_continuous(sec.axis = sec_axis(~./100,
name= expression(paste("B", "(", mu, "M)")))) +
scale_linetype_manual(values = 1:2) +
theme_classic(base_size = 16) +
ylab(bquote(A ~ (mu~M))) +
xlab("")