logo
down
shadow

Dataframe to matrix conversion using tapply turns zeros to NAs


Dataframe to matrix conversion using tapply turns zeros to NAs

By : XYlearn
Date : November 22 2020, 03:01 PM
wish help you to fix your issue I need to convert a dataframe to a matrix and I am using the following code: , Add in default = 0 as a parameter to your existing code to make:
code :
LoggAbundTGLMSOagg <- tapply(AbundTGLMSOagg$occurrence,list
                      (AbundTGLMSOagg$plot,AbundTGLMSOagg$species),mean, default = 0)


Share : facebook icon twitter icon
R list within matrix to dataframe conversion

R list within matrix to dataframe conversion


By : Ale Ale
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further R struggles. I am using the following to extract quotations from text, with multiple results on a large datset. I am trying to have the output be a character string within a dataframe, so I can easily share this as an csv with others. , Code
code :
normalCase <- 'He said, "I am a test," very quickly.'
endCase <- 'This is a long quote, which we said, "Would never happen."'
shortCase <- 'A "quote" yo';
beginningCase <- '"I said this," he said quickly';
multipleCase <- 'When asked, "No," said Sam "I do not like green eggs and ham."'
testdata = c(normalCase,endCase,shortCase,beginningCase,multipleCase)

# extract quotations
gsub(pattern = "[^\"]*((?:\"[^\"]*\")|$)", replacement = "\\1 ", x = testdata)
[1] "\"I am a test,\"  "                            
[2] "\"Would never happen.\" "                      
[3] "\"quote\"  "                                   
[4] "\"I said this,\"  "                            
[5] "\"No,\" \"I do not like green eggs and ham.\" "
Tapply over matrix using matrix math

Tapply over matrix using matrix math


By : user3551941
Date : March 29 2020, 07:55 AM
Any of those help All, I have the following code, I'd like to make it generalized for more clusters, ie C clusters. Is there a way to do this without a loop? Here, the rows of X correspond to variables x1,x2, and T is a linear transformation of X. . , Could try doing this via tapply
code :
tapply(seq_len(ncol(X)), cluster, function(x) f(T%*%X[, x])) 
#        0        1 
# 3840.681 1238.826 
Using tapply on data with counts to add zeros and NAs

Using tapply on data with counts to add zeros and NAs


By : krunal shah
Date : March 29 2020, 07:55 AM
may help you . I have a DB composed of: Species ID (as factor), counts, site, visit, year. Find a subset in here [Google Drive] , Given your data is in data.frame df
code :
library(reshape2)

tmp <- dcast(df, site + visit + year ~ species, value.var = 'counts', fill = 0)
df <- melt(tmp, id.vars = c('site', 'visit', 'year'), variable.name = 'species', value.name = 'counts')
y <- tapply(df$counts, list(df$species, df$site, df$visit, df$year), sum)
Conversion of pandas dataframe to sparse key-item matrix with composite key

Conversion of pandas dataframe to sparse key-item matrix with composite key


By : Doron Fital
Date : March 29 2020, 07:55 AM
This might help you I have a data frame of 3 columns. Col 1 is a string order number, Col 2 is an integer day, and Col 3 is a product name. I would like to convert this into a matrix where each row represents a unique order/day combination, and each column represents a 1/0 for the presence of a product name for that combination. , Here's a NumPy based approach to have an array as output -
code :
a = df[['ord_nb','day']].values.astype(int)
row = np.unique(np.ravel_multi_index(a.T,a.max(0)+1),return_inverse=1)[1]
col = np.unique(df.prd.values,return_inverse=1)[1]
out_shp = row.max()+1, col.max()+1
out = np.zeros(out_shp, dtype=int)
out[row,col] = 1
from scipy.sparse import coo_matrix

d = np.ones(row.size,dtype=int)
out_sparse = coo_matrix((d,(row,col)), shape=out_shp)
In [232]: df
Out[232]: 
  ord_nb day prd
0      1   1   A
1      1   1   B
2      1   2   B
3      1   2   C
4      1   2   D

In [233]: out
Out[233]: 
array([[1, 1, 0, 0],
       [0, 1, 1, 1]])

In [241]: out_sparse
Out[241]: 
<2x4 sparse matrix of type '<type 'numpy.int64'>'
    with 5 stored elements in COOrdinate format>

In [242]: out_sparse.toarray()
Out[242]: 
array([[1, 1, 0, 0],
       [0, 1, 1, 1]])
My input matrix does not contain zeros but i get zeros when I print the matrix.The problem description is given below

My input matrix does not contain zeros but i get zeros when I print the matrix.The problem description is given below


By : user3558549
Date : March 29 2020, 07:55 AM
wish help you to fix your issue The code within your while(dThe issue that you're having likely arises on this loop:
code :
for(i=lr;i>=r;i--) {
    b[i][lc]=a[i+1][lc];
}
#include <stdio.h>
#include <stdlib.h>
int main()

{
  int m, n, repetitions;
  long i, j;
  scanf("%d %d %d", &m, &n, &repetitions);
  long **a;
  a = (long **)malloc(m * sizeof(long *));
  for (i = 0; i < m; i++) {
    a[i] = (long *)malloc(n * sizeof(long));
  }
  for (i = 0; i < m; i++) {
    for (j = 0; j < n; j++) {
      scanf("%ld", &a[i][j]);
    }
  }

  long **b;
  b = (long **)malloc(m * sizeof(long *));
  for (i = 0; i < m; i++) {
    b[i] = (long *)malloc(n * sizeof(long));
  }

  while (repetitions--) {
    // Upper-left, lower-row, lower-column
    int ul = 0, lr = m - 1, lc = n - 1;

    // Perform a single position rotation, from the outer ring working in. Stop
    // when either the width or height of the ring is 1.
    while (ul < lr && ul < lc) {
      // Shift left-edge downwards
      for (int rr = ul; rr < lr; ++rr) b[rr + 1][ul] = a[rr][ul];

      // Shift bottom-edge rightwards
      for (int cc = ul; cc < lc; ++cc) b[lr][cc + 1] = a[lr][cc];

      // Shift right-edge upwards
      for (int rr = lr; rr > ul; --rr) b[rr - 1][lc] = a[rr][lc];

      // Shift top-edge leftwards
      for (int cc = lc; cc > ul; --cc) b[ul][cc - 1] = a[ul][cc];

      // Shift upper-left corner of ring to the right and down by 1.
      ++ul;
      // Shift bottom-edge of ring up by 1.
      --lr;
      // Shift right-edge of ring to the left by 1.
      --lc;
    }

    for (i = 0; i < m; i++) {
      for (j = 0; j < n; j++) {
        a[i][j] = b[i][j];
      }
    }
  }
  for (i = 0; i < m; i++) {
    for (j = 0; j < n; j++) {
      printf("%ld ", a[i][j]);
    }
    printf("\n");
  }
  return 0;
}
Related Posts Related Posts :
  • How to define a function that calls shiny functions?
  • How to count number of observations in a "n" dimensional range in R
  • Superimposing asymmetric t-distribution using ggplot2
  • Makefile to render all targets of all .Rmd files in directory
  • Authentication failure with rdrop2
  • DT data table display error
  • Issue when adding new rows (with nested dataframes within) to a dataframe
  • R-How to compare two dataframe and update list column value
  • Series vector for approximating pi
  • what is difference between "variance explained " in Random Forest and "merror" in XGBoost
  • R - Cast dataframe on unique rows - reshape2
  • ggplot2: plot correct proportions using geom_bar
  • Speedup query for R data.table - can this two-argument function be applied by group more quickly?
  • apply a function to several columns at once with mutate
  • R 'cowplot' neatly produce gridded plot with shared (common) legends and unique legends
  • Repeat R script for many times and save results to text file
  • How to negative lookbehind for special characters
  • data.table inner join produces error when no match is found
  • Create a new column base on existing column, but row above
  • Is there a way to visualize the process of source() in RStudio?
  • google places api consumes 10 request but I am doing only 1
  • Statistical mode of a categorical variable in R (using mlv)
  • Using for-loop to mutate a data.frame in r
  • Make plot with regression line for mixed model
  • Shortcut to select matces cases in R studio
  • vectoriced norm/matrix multiplication
  • Negative log10 transformation in R
  • Plot data with duplicate points
  • Visualizing crosstab tables with a plot in R - changing colours
  • How to manually modify automated numbers and labels in plot
  • How can I follow any redirections of a url in R?
  • Add jitter to box plot using markers in plotly
  • Adding an extra item to the legend
  • ggplot fills in data in the wrong order
  • Convert list to data frame
  • R: filtering by list(s) of strings and returning all results that start with the content of the lists
  • R:How to attach parts of a data frame with different headers and/or an overflowing piece of the dat frame
  • How to use 'par' for manipulating plot margins?
  • Can dplyr::case_when return mix of NAs and non-NAs?
  • Text preprocessing and topic modelling using text2vec package
  • Uploading multiple files in Shiny, process the files, rbind the results and return a download
  • R levelplot: color green-white-red (white on 0) according to one variable, but show the values of another variable
  • Why [i] doesn't point to the starting point in a vector
  • In R after generating a mvrnorm distribution, Y, what does Y[,1] do?
  • expand a data frame to have as many rows as range of two columns in original row
  • Getting started with R and CFA
  • Re order x-axis in ggplot so time goes from 12AM to 11PM in R
  • R - Automatically stack every nth column of a data frame and save them as new objects
  • How to format dplyr output in R into doubles (or other workable format)?
  • Smallest multiple of 1:20 - How can I make it quicker?
  • How to specify the size of a graph in ggplot2 independent of axis labels
  • How can I find the number of a vector's elements in another vector?
  • ROC curve from train/test set in caret R package
  • Random Forest for a mixture of categorical,numeric and "unwanted" variables which include missing values
  • extract certain data from multiple excel files with R
  • Matrix with counts of wins and losses between methods in R
  • Grouping string variables from a dataframe by best string match to make subsets
  • Reorder does not work after adding second geom_points
  • cover POS data formate to the one can apply Arules (Apriori)
  • Matching values between data frames based on overlapping dates
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org