Shiny: renderDataTable throws error when renaming columns in data.frame - r

I have a Shiny app that is creating a network visualisation. When the user clicks a node in the visualisation, a table is displayed detailing information about this node. All of this works beautifully as seen in the code below:
output$shiny_return <- renderDataTable({
if(!is.null(input$current_node_id)) {
kwic.file <- paste0(input$current_node_id, "_6.csv")
kwic.data <- read.csv(file.path(config.analysis.basedir, config.kwic.basedir, kwic.file))
output.table <- data.frame(getLetterUrlFromFile(kwic.data$file), kwic.data$left, kwic.data$keyword, kwic.data$right)
}
}, escape = F)
However, the column names in the data table aren't what I want them to be in the output so I simply want to rename the columns in the output. I tried doing this by adding one line of code after the creation of the data.frame:
colnames(output.table) <- c("Letter", "Left Context", "Keyword", "Right Context")
Now the function throws an error:
Error: 'data' must be 2-dimensional (e.g. data frame or matrix)
I have tried renaming the columns using plyr as well and that doesn't seem to work. If I remove this one line, everything is fine (I just have ugly column names). Is there something I'm missing? Should I be renaming the column names in a different manner?

Related

rbind and bind_rows not working on Mac but works on Windows

I am working on importing multiple csv files which contain data from climate sensors (temp, humidity, etc.). My code is below. First, I get a list of all the files I am importing and the length of that list. I then have a for loop cycling through each file, inside of that an if loop checking if the file is a csv. In the if loop, the code reads the file in and temporarily stores it in "store". Afterwards, a data frame which holds all of the data, called "main", and "store" are combined using rbind.
file_list <- list.files(".")
num_files <- length(file_list)
main <- data.frame()
for (i in 1:num_files){
check <- stri_length(file_list[i])
if (substr(file_list[i],start = check - 2, stop = check) == "csv"){
store <- read.csv(file_list[i])
main <- rbind(main, store)
}
However, when I run the code, I get the following error: "Error in rbind(deparse.level, ...) : numbers of columns of arguments do not match"
There are a few things that are interesting with this code and error. First, when I run this code on a windows computer, it works brilliantly with no error, but it does not work on my MAC. Second, all the columns in the imported data are identical, so rbind should work, and it does on a windows. Third, when I examine the empty data frame "main," it has very weird column names that do not match up with the data, for example, X21092, X16, X5.2, etc... Hence, it will not bind the temporarily stored data and the empty data frame. Now, when I do not use rbind and try something different such as bind_rows, I get the same wacky column names that do not match up with anything, so the problem is not with rbind. Finally, when I run codes that use a very similar for loop with rbind on my MAC, they work just as expected.
I have tried clearing everything, such as the environment, using the code on a new file, and uninstalling R and RStudio, all of which yield the same result and error.
Is the some reason I am getting this error on my MAC and what should I do to fix it?
Here is a photo of the data frame when it runs correctly
enter image description here
Here is an image of the data frame when I get the error on my MAC
enter image description here

Analyze code in dataframe with Tidycode in R

I am trying to take R code, stored in cells of the content column of a dataframe, and analyze the functions used by applying the Tidycode package. However, I first need to convert the data to a Matahari tibble before applying an unnest_calls() function.
Here is the data:
data <- read.csv("https://github.com/making-data-science-count/TidyTuesday-Analysis/raw/master/db-tmp/cleaned%20database.csv")
I have tried doing this in a number of different ways, including extracting each row (in the content column ) as an Rfile and then reading it back in with Tidycode calls, for example:
tmp<-data$content2[1])
writeLines(tmp, "tmp.R") #I've also used save() and write()
rfile<-tidycode::read_rfiles("tmp.R")
But, I keep getting errors such as: "Error in parse(text = x) : <text>:1:14: unexpected symbol
1: library(here)library"
Ultimately, what I would like to do is analyze the different types of code per file, and keep that linked with the other data in the data dataframe, such as date and username.
Any help would be greatly appreciated!

R / openxlsx / Finding the first non-empty cell in Excel file

I'm trying to write data to an existing Excel file from R, while preserving the formatting. I'm able to do so following the answer to this question (Write from R into template in excel while preserving formatting), except that my file includes empty columns at the beginning, and so I cannot just begin to write data at cell A1.
As a solution I was hoping to be able to find the first non-empty cell, then start writing from there. If I run read.xlsx(file="myfile.xlsx") using the openxlsx package, the empty columns and rows are automatically removed, and only the data is left, so this doesn't work for me.
So I thought I would first load the worksheet using wb <- loadWorkbook("file.xlsx") so I have access to getStyles(wb) (which works). However, the subsequent command getTables returns character(0), and wb$tables returns NULL. I can't figure out why this is? Am I right in that these variables would tell me the first non-empty cell?
I've tried manually removing the empty columns and rows preceding the data, straight in the Excel file, but that doesn't change things. Am I on the right path here or is there a different solution?
As suggested by Stéphane Laurent, the package tidyxl offers the perfect solution here.
For instance, I can now search the Excel file for a character value, like my variable names of interest ("Item", "Score", and "Mean", which correspond to the names() of the data.frame I want to write to my Excel file):
require(tidyxl)
colnames <- c("Item","Score","Mean")
excelfile <- "FormattedSheet.xlsx"
x <- xlsx_cells(excelfile)
# Find all cells with character values: return their address (i.e., Cell) and character (i.e., Value)
chars <- x[x$data_type == "character", c("address", "character")]
starting.positions <- unlist(
chars[which(chars$character %in% colnames), "address"]
)
# returns: c(C6, D6, E6)

Trouble accessing the first column of a dataset in R

I am a beginner in R. I work in RStudio
After importing my dataset with the function:
mydata <- read.table("dataset.txt",sep="\t",dec=",", h=T, row.names=1)
the file is imported and I can see it in RStudio. Then, I would like to look at my data:
table (column2, column3) # it does work and give me the table
everything looks OK. However, if I ask for the First column
table (column1, column2) # it doesn't work!
I received the error message:
"Error in table(column1) : object 'ID_site' not found"
It seems the first column is not part of my dataset...
Do you know Why? Is there an option to choose before data importation?
Try removing the row.names=1 part from your read.table call. When you do that, R takes the first column of your dataset and uses it as the rownames of your data frame. That, in turn removes the ID of the column, which is why R says your "ID_site" column can't be found.

How can I use a variable to get an Input$ in Shiny?

I am new to R and I am creating a shiny application to read a csv and filter data. I am reading the csv file, then creating dropdowns with a loop using the column names and the unique values:
output$dropdowns <- renderUI({
if (is.null(x())) {
return(NULL)
}
lapply(1:ncol(x()), function(i) {
selectInput(names(x()[i]), names(x()[i]), c("ALL", unique(as.character(x()[,i]))))
})
I am now trying to filter the data based on the input from the user. To get the input I am trying to loop through the names (names(x)[i]), which is the ID of the selectinput and get the value. But whenever I use input$names(x)[i], I get the following error:
Error: attempt to apply non-function.
I have tried to test this using an actual header (e.g. input$testHeader) and this works fine. But when I try to do the same with a variable, e.g.:
a < - "testHeader"
print(input$a).
This returns NULL. I assume it is looking for a selecinput with ID "a" and cannot find it. But I have no idead how else to try?
Any help would be great.
Thanks.
input is just a reactivevalues object so you can use [[:
print(input[[a]])

Resources