更改 R shiny 中的列名称
Change column name in R shiny
我在更改数据集 df1() 中的列名称时遇到问题。我准备 selectInput(要重命名的列名)和 textInput(目标列名)。但是我的版本不起作用(下面的代码)。更好地说,它有效,但仅适用于“静态”新列名,当我使用 textInput 时,它会给我一个错误 unexpected '='。有人可以帮助我吗?
SERVER:
output$to_rename<- renderUI({
choice <- names(df1())
selectInput('to_rename', label = 'Choose column to rename: ', choices = choice)
})
output$target_rename<- renderUI({
textInput('target_rename', label = 'Write new column name: ', value = "Your_new_colname")
})
observeEvent(input$ren_col, {
df1(df1() %>% rename(
input$target_rename = input$to_rename #when I use: new_name = input$to_rename it works
#and selected column will be rename to "new_name"
))
})
##############################################################################
UI:
uiOutput("to_rename"),
uiOutput("target_rename"),
actionButton("ren_col", "Rename"),
您可以使用 !!
以编程方式访问变量名。
代表:
## mimic shiny's `input$` variable:
input <- list(oldname="cyl", newname="newcyl")
head(mtcars) %>%
rename(!!input$newname := !!input$oldname)
# mpg newcyl disp hp drat wt qsec vs am gear carb
# Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
# Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
# Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
# Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
# Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
# Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
我在更改数据集 df1() 中的列名称时遇到问题。我准备 selectInput(要重命名的列名)和 textInput(目标列名)。但是我的版本不起作用(下面的代码)。更好地说,它有效,但仅适用于“静态”新列名,当我使用 textInput 时,它会给我一个错误 unexpected '='。有人可以帮助我吗?
SERVER:
output$to_rename<- renderUI({
choice <- names(df1())
selectInput('to_rename', label = 'Choose column to rename: ', choices = choice)
})
output$target_rename<- renderUI({
textInput('target_rename', label = 'Write new column name: ', value = "Your_new_colname")
})
observeEvent(input$ren_col, {
df1(df1() %>% rename(
input$target_rename = input$to_rename #when I use: new_name = input$to_rename it works
#and selected column will be rename to "new_name"
))
})
##############################################################################
UI:
uiOutput("to_rename"),
uiOutput("target_rename"),
actionButton("ren_col", "Rename"),
您可以使用 !!
以编程方式访问变量名。
代表:
## mimic shiny's `input$` variable:
input <- list(oldname="cyl", newname="newcyl")
head(mtcars) %>%
rename(!!input$newname := !!input$oldname)
# mpg newcyl disp hp drat wt qsec vs am gear carb
# Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
# Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
# Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
# Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
# Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
# Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1