首页 > 解决方案 > 在闪亮中重新编码变量

问题描述

我在用闪亮的方式重新编码一些值时遇到了一点问题。似乎我的值被整合为因素,但我想将它们用作数字变量。

我试图解释。这是一个最小的例子:

datensatz_patient <- reactive({datensatz <- input$datensatz
                               infile    <- read.table(datensatz$datapath, header=TRUE, strip.white = TRUE, stringsAsFactors = FALSE, sep=";",dec=",", na = -77)

BSI_dat           <- reactive(subset(datensatz_patient(), select = c(Base_BSI_v1:Base_BSI_v53))

BSI.sub_soma      <- reactive(subset(BSI_dat(), select = c(2, 7, 23, 29, 30, 33, 37))) 

BSI.soma.SW       <- reactive(apply(BSI.sub_soma(),1, mean, as.numeric = TRUE, na.rm = TRUE))

BSI.soma.T_m      <- reactive(recode(BSI.soma.SW(), "0 = 41; 0.17 = 50; 1 = 60;  1.5 = 70; 2 = 80; 3.71 = 112"))


output$test8.1 <- renderTable(BSI.soma.SW())
output$test8.2 <- renderTable(BSI.soma.T_m())

我的问题是,重新编码BSI.soma.SW无法正常工作。使用整数(1 或 2)BSI.soma.T_m获取新值(1 = 60 或 2 = 80)。对于十进制数字,它不起作用。不重新编码小数。我的错在哪里?我应该怎么办?

谢谢您的帮助

标签: rshiny

解决方案


我认为您在recode表达式中替换的格式已关闭。很难准确地说出,因为您没有包含数据样本,但我生成了一个应该足够的数字向量:

recode示例中的表达式与数字向量一起使用并不能给出正确的答案:

recode(c(0,1,1,.17,2,3.71), "0 = 41; 0.17 = 50; 1 = 60;  1.5 = 70; 2 = 80; 3.71 = 112")
[1] NA                                                        
[2] "0 = 41; 0.17 = 50; 1 = 60;  1.5 = 70; 2 = 80; 3.71 = 112"
[3] "0 = 41; 0.17 = 50; 1 = 60;  1.5 = 70; 2 = 80; 3.71 = 112"
[4] NA                                                        
[5] NA                                                        
[6] NA                                                        
Warning message:
Unreplaced values treated as NA as .x is not compatible. Please specify replacements exhaustively or supply .default

如果我们固定Replacements为多个逗号分隔的命名向量(使用 anL使它们成为显式整数。请参阅此答案:What's the difference between `1L` and `1`?),我们得到正确的结果:

recode(c(0,1,1,.17,2,3.71), '0' = 41L, '0.17' = 50L, '1' = 60L,  '1.5' = 70L, '2' = 80L, '3.71' = 112L)
[1]  41  60  60  50  80 112

推荐阅读